Tre*_*key 1 c++ assembly move lifetime copy-constructor
我在生命结束前将一些对象传递给构造函数.
int main(){
//I wanted to avoid short string optimization in this example.
const std::string a(25,"a");
const std::string b(25,"b");
const std::string c(25,"c");
Foo f{a,b,c};
}
Run Code Online (Sandbox Code Playgroud)
我为Foo的构造函数考虑了两个选项.
const& (调用字符串的复制构造函数):
Foo(const std::string & a,
const std::string & b,
const std::string & c)
:a(a)
,b(b)
,c(c)
{}
Run Code Online (Sandbox Code Playgroud)
std::move (调用字符串的移动构造函数):
Foo(std::string a,
std::string b,
std::string c)
:a(std::move(a))
,b(std::move(b))
,c(std::move(c))
{}
Run Code Online (Sandbox Code Playgroud)
随着-01上gcc 7,我得到了以下结果:
+-------------+-----------------------+
| constructor | assembly instructions |
+-------------+-----------------------+
| const& | 192 |
| move | 264 |
+-------------+-----------------------+
Run Code Online (Sandbox Code Playgroud)
为什么const&减少指示?
我认为移动比通过复制构造函数创建新字符串便宜.
当这些参数的生命周期结束时,将变量作为构造函数参数传递的经验法则是什么?
你没有调用移动构造函数.你的参数字符串是const.所以当你使用std::move它们时,结果是const std::string&&.这不会调用移动构造函数,签名需要std::string&&.