c++ - 为什么 move 比通过 const& 传递更昂贵?

标签 c++ assembly move copy-constructor lifetime

我将一些对象在其生命周期结束前传递给构造函数。

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};
}

对于 Foo 的构造函数,我考虑了两个选项。

const&(调用字符串的复制构造函数):

Foo(const std::string & a,
    const std::string & b,
    const std::string & c)
:a(a)
,b(b)
,c(c)
{}

std::move(调用字符串的 move 构造函数):

Foo(std::string a,
    std::string b,
    std::string c)
:a(std::move(a))
,b(std::move(b))
,c(std::move(c))
{}  

gcc 7 上使用 -01,我得到了以下结果:

+-------------+-----------------------+
| constructor | assembly instructions |
+-------------+-----------------------+
| const&      |                   192 |
| move        |                   264 |
+-------------+-----------------------+

为什么const&指令少?
我认为 move 比通过复制构造函数创建新字符串更便宜。

将变量作为构造函数参数传递的经验法则是什么
这些参数的生命周期何时结束?

最佳答案

您没有调用 move 构造函数。您的参数字符串是常量。因此,当您对它们使用 std::move 时,结果是 const std::string&&。这不会调用 move 构造函数,其签名采用 std::string&&

关于c++ - 为什么 move 比通过 const& 传递更昂贵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39864497/

相关文章:

c++ - 一次多个动画

c - 我正在编写自己的 JIT 解释器。如何执行生成的指令?

c++ - 成员函数返回成员变量的右值引用

c# - 如何在.net core中使用 "System.Net.ServicePointManager"?

c++ - 使用智能指针进行部分特化的正确语法

c++ - 如何在循环中改变容器中的元素?

c++ - 如何修复这些编译器错误?

assembly - 尝试使用 x86 程序集查找数组中的最小值时出现意外输出

c - 汇编中的 lea 运算符使用寄存器的三参数算术

c++ - std::string move 构造函数是否真的 move ?