jas*_* na 4 move move-semantics c++11
所以假设我有以下功能:
void foo(std::string strParam) // pass-by-value
{
// function-body
}
Run Code Online (Sandbox Code Playgroud)
因此,foo(字符串)的strParam将通过复制(如果arg是左值)或移动(如果arg是rvalue)创建.
众所周知,
foo("blah"); // rvalue; so string move constructor invoked for strParam.
Run Code Online (Sandbox Code Playgroud)
与,
string bar = "blah";
foo(bar); // lvalue; so string copy constructor invoked for strParam.
Run Code Online (Sandbox Code Playgroud)
再次,
string bar = "blah";
foo(move(bar)); // xvalue; so move constructor.
Run Code Online (Sandbox Code Playgroud)
以及命名的右值引用变量
string &&temp = // can be whatever
foo(temp); // *named* rvalue reference IS a lvalue; so copy constructor.
Run Code Online (Sandbox Code Playgroud)
所以我想这意味着什么,
string &&movedBar = move(bar);
foo(movedBar); // it actually invokes copy constructor.
Run Code Online (Sandbox Code Playgroud)
如此调用,
foo(move(bar))
Run Code Online (Sandbox Code Playgroud)
不同于
string&& movedBar = move(bar);
foo(movedBar)
Run Code Online (Sandbox Code Playgroud)
因为一个是未命名的右值引用(xvalue)而另一个是名为rvalue的引用(左值)
那是对的,对吗?
一个修正:
foo("blah"); // rvalue; so string move constructor invoked for strParam.
Run Code Online (Sandbox Code Playgroud)
这实际上调用的std::string是带有a const char*而不是std::string移动构造函数的构造函数.这是std::string重载集中唯一的构造函数 - 其他一切都涉及多个用户定义的转换.
在其他每一点上,你是对的.总结一下:
foo("blah"); // calls string constructor that takes a const char*
foo(bar); // calls string copy ctor
foo(move(bar)); // calls string move ctor
string&& movedBar = move(bar);
foo(movedBar); // calls copy ctor
Run Code Online (Sandbox Code Playgroud)
更新:正如Tobias在评论中指出的那样,foo("blah")实际上会调用两个构造函数,就像它实际上一样foo(string("blah")).首先构造一个临时字符串,"blah"并将临时字符串移入strParam.然而,第二步可能会被省略,因为这string strParam(string("blah"))是多余的.这可以通过delete自定义窗口小部件的移动构造函数或使用编译来验证-fno-elide-constructors.
或者,我喜欢看它,我们都是正确的.在const char*被调用和串动构造函数被调用(ISH〜?).
| 归档时间: |
|
| 查看次数: |
131 次 |
| 最近记录: |