gpt4 book ai didi

c++ - 理解 c++11 右值、 move 语义和性能

转载 作者:可可西里 更新时间:2023-11-01 15:03:25 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
What happens if I return literal instead of declared std::string?

考虑以下代码

string getName () {
return "meme";
}

string name = getName();

getName() 函数返回一个临时对象。在 C++03 中,我理解 string 的复制构造函数被调用并且临时对象被销毁。实际上,编译器(至少在 GCC 4.7 中)似乎通过不创建对象 name 而是将其替换为临时对象本身而不是销毁临时对象来优化第 5 行。 (我尝试使用 MyVector 类,而不是 std::string)

如 C++11 标准中所定义,

  1. getName() 是否返回右值?

  2. 在上面的第 5 行中,调用了字符串的哪个构造函数( move 或复制)?我是否必须调用 std::move() 来调用 move 构造函数?

  3. 使用 move 语义,它的效率是否低于编译器提供的“复制省略”优化?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com