fre*_*low 10 c++ rvalue-reference c++11
在C++ 11中,无论表示调用该方法的对象的表达式是左值还是右值,都可以重载方法.如果我回到*this
从通过右值调用的方法,我需要明确move
的*this
或不?
Foo Foo::method() &&
{
return std::move(*this); // Is this move required or not?
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,我不能简单地在我的编译器上测试这个,因为g ++还不支持这个功能:(
的类型始终*this
是左值:
\xc2\xa79.3.2 [class.this] p1
\n\n\n在非静态 (9.3) 成员函数体中,关键字
\nthis
是纯右值表达式,其值是调用该函数的对象的地址。this
类的成员函数中的类型X
是X*
。[...]
\xc2\xa75.3.1 [expr.unary.op] p1
\n\n\n一元运算
\n*
符执行间接寻址:应用它的表达式应是指向对象类型的指针,或指向函数类型的指针,结果是引用表达式所指向的对象或函数的左值。
std::move
因此,如果您想调用移动构造函数,则需要这样做。
下面的代码片段表明:
\n\n#include <iostream>\n#include <utility>\n\nstruct test{\n test(){}\n test(test const&){ std::cout << "copy ctor // #1\\n"; }\n test(test&&){ std::cout << "move ctor // #2\\n"; }\n\n test f_no_move() &&{ return *this; }\n test f_move() &&{ return std::move(*this); }\n};\n\nint main(){\n test().f_no_move(); // #1\n test().f_move(); // #2\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n使用 Clang 3.1(我知道的唯一实现引用限定符的编译器),我得到以下输出:
\n\n\n\n$ clang++ -std=c++0x -stdlib=libc++ -pedantic -Wall t.cpp
\n
\n $ ./a.out
\n 复制构造函数 // #1
\n 移动构造函数 // #2
归档时间: |
|
查看次数: |
1012 次 |
最近记录: |