例如:
Beta_ab&&
Beta::toAB() const {
return move(Beta_ab(1, 1));
}
Run Code Online (Sandbox Code Playgroud) 函数应该返回RValue Reference是否有原因?技巧,技巧,或成语或模式?
MyClass&& func( ... );
Run Code Online (Sandbox Code Playgroud)
我知道一般返回引用的危险,但有时我们会这样做,不管我们(T& T::operator=(T)只是一个惯用的例子).但是怎么样T&& func(...)?我们会从中获得这样的一般场所吗?与仅仅客户端代码相比,当编写库或API代码时,可能会有所不同?
它在[C++ 11:12.8/31]中说明:
复制/移动操作的省略,称为复制省略,允许[...]:
- 在具有类返回类型的函数的return语句中,当表达式是具有与函数返回类型相同的cv-unqualified类型的非易失性自动对象(除函数或catch子句参数之外)的名称时,通过将自动对象直接构造到函数的返回值中,可以省略复制/移动操作
这意味着
#include <iostream>
using namespace std;
struct X
{
X() { }
X(const X& other) { cout << "X(const X& other)" << endl; }
};
X no_rvo(X x) {
cout << "no_rvo" << endl;
return x;
}
int main() {
X x_orig;
X x_copy = no_rvo(x_orig);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
将打印
X(const X& other)
no_rvo
X(const X& other)
Run Code Online (Sandbox Code Playgroud)
为什么需要第二个拷贝构造函数?编译器不能简单地延长x的生命周期吗?
我将函数的某些返回值绑定到const左值引用,但是在const lvalue引用的生命周期结束之前删除了该对象.
在以下示例中,Foo对象在foo结束的生命周期之前被销毁:
#include <iostream>
#include <string>
struct Foo
{
~Foo()
{
std::cout << "Foo destroyed: " << name << std::endl;
}
std::string name;
};
Foo&& pass_through(Foo&& foo)
{
return std::move(foo);
}
int main()
{
const Foo& foo = pass_through({"some string"});
std::cout << "before scope end" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
Foo被破坏:
范围结束前的一些字符串
住在coliru:1
我以为你可以绑定const T&任何东西.返回是不好的做法T&&,应该按价值返回?
我在这里的cpprestsdk偶然发现了这个:
inline utility::string_t&& to_string_t(std::string &&s) { return std::move(s); }
Run Code Online (Sandbox Code Playgroud)
https://github.com/Microsoft/cpprestsdk/blob/master/Release/include/cpprest/asyncrt_utils.h#L109
非常混乱,因为Windows版本to_string_t(由预处理器宏调度)返回值:
_ASYNCRTIMP utility::string_t __cdecl …Run Code Online (Sandbox Code Playgroud)