为什么c ++会在以下情况下生成构造函数?

时间:2016-03-23 11:46:36

标签: c++ testing move-semantics

我有一个A级

struct A{
    A(){}

    A(int x): d(x) {}

    A(const A& a): d(a.d) {
        std::cout << "copy construction" << std::endl;
    }

    A(A&& a): d(a.d){
        std::cout << "move construction" << std::endl;
    }

    A& operator=(const A& a){
        std::cout << "copy assignment" << std::endl;
        d = a.d;
        return *this;
    }

    A& operator=(A&& a){
        std::cout << "move assignment" << std::endl;
        d = a.d;
        return *this;
    }

    int d;
};

和函数func

A func(){
    return A(3);
}

如果我这样做

A x;
x = func();

输出是&#34;移动分配&#34;正如所料 但如果我像这样构建A

A x = func();

然后没有打印出来,好像c ++生成了自己的移动构造函数并且拒绝使用已定义的移动构造函数。

我正在使用visual studio 14

我真的很想理解这一点。

感谢您的解释。

1 个答案:

答案 0 :(得分:4)

构造函数调用已被删除。

  • 使用gcc,您可以使用-fno-elide-constructors停用它。
  • msvc没有等效选项。
相关问题