所以,这在 GCC、CLANG 和 MSVC 上编译得很好,但给出了不同的输出:
#include <iostream>
using namespace std;
class A {
public:
A() {
cout << this << " def" << endl;
}
A(const A&) {
cout << this << " copy" << endl;
}
A(A&&) {
cout << this << " move" << endl;
}
A& operator= (const A&) {
cout << this << " copy=" << endl;
return *this;
}
A& operator= (A&&) {
cout << this << " move=" << endl;
return *this;
}
~A() {
cout << this << " ~A" << endl;
}
};
A f() {
A a;
return a;
}
int main(){
A a = f();
}
使用 GCC 和 CLANG 输出:
- 0xbfad67cf def
- 0xbfad67cf ~A
虽然 MSVC 输出符合预期(C++11 标准):
- 0039FA3B 定义
- 0039FA3B 移动
- 0039FA3B~A
因此,使用 MSVC 编译的代码调用移动构造函数,而使用 GCC 和 CLANG 编译的代码不调用移动构造函数。 我也尝试禁用优化,但仍然得到相同的输出。更奇怪的是,当我将 f() 更改为返回 A() 时,即使在 MSVC 上也不会调用移动构造函数。
编译器版本:
- gcc: 4.7.2 版 (GCC)
- clang: 3.2 版(标签/RELEASE_32/final) 目标:i386-pc-linux-gnu
平台:Linux/ArchLinux
最佳答案
关于c++ - 使用 clang 和 gcc 编译时代码不调用 Move 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15664254/