所以,这在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 def 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
So, this compiles just fine on GCC, CLANG and MSVC but gives different output:
#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(); }With GCC and CLANG outputs:
0xbfad67cf def 0xbfad67cf ~AWhile with MSVC out is as expected (C++11 standard):
0039FA3B def 0039FA3B move 0039FA3B ~ASo, code compiled with MSVC calls move constructor, while with GCC and CLANG move constructor is not called. I also tried with optimizations disabled, and still get the same output. What is more strange is that when I change f() to return A(), move constructor is not called even on MSVC.
Compiler versions:
gcc: version 4.7.2 (GCC) clang: version 3.2 (tags/RELEASE_32/final) Target: i386-pc-linux-gnuPlatform: Linux/ArchLinux
最满意答案
那就是返回值优化
http://en.wikipedia.org/wiki/Return_value_optimization
编译器优化的返回对象不是被复制而是被移除
That is return value optimization
http://en.wikipedia.org/wiki/Return_value_optimization
compiler optimized returned object not to be copyed than removed
更多推荐
发布评论