gpt4 book ai didi

c++ - 为什么 RVO 不适用于移动构造函数?

转载 作者:太空宇宙 更新时间:2023-11-04 16:20:30 24 4
gpt4 key购买 nike

我正在尝试测试 RVOrvalue 引用。这是代码:

#include <iostream>

using namespace std;

class B{
public:
int i;

B(){
i = 0;
cout << "B() " << i << endl;
}

B(const B& b){
i = 1;
cout << "B(const B&) " << i << endl;
}

B(const B&& b){//if remove this constructor, then call B(const B& b)
i = 2;
cout << "B(const B&&) " << i << endl;
}

~B(){
cout << "~B() " << i << endl;
}
};

B f(){
B b;
return b;
}

int main(){

B b = f();

return 0;
}

输出是:

B() 0
B(const B&&) 2
~B() 0
~B() 2

环境:WIN8、Visual Studio 2012 Express

这意味着调用了移动构造函数:B(const B&&)。提出两个问题:

  • 为什么这里没有应用RVO
  • 为什么调用复制构造函数:B(const B&)
  • 如果我删除 B(const B&&),则会调用 B(const B&)。奇怪的输出:

    B() 0
    B(常量 B&) 1
    ~B() 0
    ~B() 1

这是我找到的引用资料:


编辑:
移动构造函数应该是B(B&&)。关键是为什么移动构造函数被称为不是复制构造函数

最佳答案

Why RVO is not applied here?

这不仅仅是执行优化。 g++ 在使用 -O2 时确实在这里使用了 RVO。您应该在编译器上启用优化以对此进行测试。但是,请注意,即使某些编译器可能会应用 RVO,它也不是强制性的,因此您可能会看到使用不同编译器的不同结果。

Why NOT call the move constructor: B(const B&)?

这是一个拷贝构造函数。它正在调用移动构造函数,这在此处更匹配。

If I remove the B(const B&&), then B(const B&) is called. Weird!

不,这并不奇怪。如果您定义复制构造函数,则编译器不会隐式定义移动构造函数。因此,编译器正在选择复制构造函数,因为没有可用的移动构造函数。

请注意,您的移动构造函数应采用非 const 右值引用:

B(B&& b) {
// ...
}

否则,您最终只会做与复制构造函数中相同的事情。

关于c++ - 为什么 RVO 不适用于移动构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17288274/

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