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

标签 c++ visual-c++ gcc c++11 clang

所以,这在 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

最佳答案

也就是返回值优化

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

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

关于c++ - 使用 clang 和 gcc 编译时代码不调用 Move 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15664254/

相关文章:

c++ - Qt Creator LNK1104 : cannot open file 'glu32.lib'

c - 如何仅从依赖库中删除符号?

c - HDF-EOS 配置失败, "C compiler cannot create executables"

c++ - 在 SWIG 中包含 OpenCV core.hpp 时出现语法错误

c++ - 输出声明堆在释放后被修改,但没有添加到堆中

c++ - 如何检索整个 va_list 输入

c++ - header 未刷新 - Visual C++ 2012

c - char类型变量的内存分配

c++ - QScrollArea 与动态调整 subWidgets

c++ - 为什么 Visual Studio 不在 self 赋值时发出警告 (int foo = foo;)