使用clang和gcc编译时,代码不调用Move构造函数

dak*_*akt 3 c++ gcc clang visual-c++ c++11

所以,这在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();
}
Run Code Online (Sandbox Code Playgroud)

使用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

kas*_*sak 6

这是返回值优化

http://en.wikipedia.org/wiki/Return_value_optimization

编译器优化的返回对象不是被复制而是被移除