因此,假设我有以下功能:
void foo(std::string strParam) // pass-by-value
{
// function-body
}所以foo(string)的strParam要么是通过复制(如果arg是lvalue)创建的,要么是move (如果arg是rvalue)。
大家都知道,
foo("blah"); // rvalue; so string move constructor invoked for strParam.相对于,
string bar = "blah";
foo(bar); // lvalue; so string copy constructor invoked for strParam.再一次,
string bar = "blah";
foo(move(bar)); // xvalue; so move constructor.和命名的rvalue引用变量
string &&temp = // can be whatever
foo(temp); // *named* rvalue reference IS a lvalue; so copy constructor.所以我想这意味着,
string &&movedBar = move(bar);
foo(movedBar); // it actually invokes copy constructor.所以援引,
foo(move(bar)) 是不同的
string&& movedBar = move(bar);
foo(movedBar)因为一个是未命名的rvalue引用(xvalue),另一个是rvalue引用(lvalue)。
对吧,对吧?
发布于 2015-01-30 23:02:39
一项更正是:
foo("blah"); // rvalue; so string move constructor invoked for strParam.这实际上调用了std::string构造函数,该构造函数接受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 ctorUpdate:正如Tobias在注释中指出的那样,foo("blah")实际上会调用两个构造函数,就好像它实际上是foo(string("blah"))一样。首先,从"blah"构造一个临时字符串,然后将该临时字符串移动到strParam中。然而,由于string strParam(string("blah"))是多余的,第二步可能会被删除。这可以由delete-ing (自定义小部件的移动构造器)验证,也可以通过-fno-elide-constructors进行编译。
或者,在我看来,我们都是对的。调用const char*,调用字符串移动构造函数(~ish?)。
https://stackoverflow.com/questions/28244255
复制相似问题