代码之家  ›  专栏  ›  技术社区  ›  injoy

移动语义和复制构造函数

  •  0
  • injoy  · 技术社区  · 11 年前

    我写了一个程序如下:

    #include <iostream>
    
    using namespace std;
    
    class A {
    public:
        A() {
        }
        A(A &a) {
            id = a.id;
            cout << "copy constructor" << endl;
        }
        A& operator=(A &other) {
            id = other.id;
            cout << "copy assignment" << endl;
            return *this;
        }
        A(A &&other) {
            id = other.id;
            cout << "move constructor" << endl;
        }
        A& operator=(A &&other) {
            id = other.id;
            cout << "move assignment" << endl;
            return *this;
        }
    public:
        int id = 10;
    };
    
    A foo() {
        A a;
        return a;
    }
    
    int main()
    {
        A a;
        A a2(a); // output: copy constructor
        A a3 = a2; // output: copy constructor
        a3 = a2; // output: copy assignment
        A a4 = foo(); // output: 
        a4 = foo(); // output: move assignment
        return 0;
    }
    

    我在我的Mac操作系统上编译了它。输出为:

    copy constructor
    copy constructor
    copy assignment
    move assignment
    

    我的问题是:

    1. 为什么 A a4 = foo(); 是空的吗?我认为它应该调用move构造函数。
    2. 为什么 A a3 = a2; copy constructor 而不是 copy assignment ?
    2 回复  |  直到 11 年前
        1
  •  5
  •   Lightness Races in Orbit    11 年前
    1. 因为如果编译器愿意,复制和移动可能会被它忽略。相关的构造函数必须仍然存在,但在标准中明确规定了它们可能不会被调用。(这是一个罕见的标准定义优化示例,特别是允许回报值优化也是标准定义的。)

    2. 因为使用 = 在初始化中执行构造,而不是赋值。这就是语法,这让人有些困惑。 A a3(a2) 在这方面,(本质上)是等效的。

        2
  •  0
  •   Brett Hale    11 年前

    编译器正在为以下项生成默认方法:

    A (const A &);
    A & operator = (const A &);
    

    如果您添加 const 限定符,您可能会看到您期望的结果。