0

I wrote a program as below:

#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;
}

I compiled it on my Mac OS. The output is:

copy constructor
copy constructor
copy assignment
move assignment

My question are:

  1. Why the output of A a4 = foo(); is empty? I thought it should call the move constructor.
  2. Why the output of A a3 = a2; is copy constructor instead of copy assignment?
4

2 回答 2

5
  1. 因为如果编译器愿意,复制和移动可能会被忽略。相关的构造函数必须仍然存在,但标准中明确规定它们可能不会被调用。(这是标准定义优化的罕见示例,特别是允许返回值优化也是标准定义的。)

  2. 因为=in 初始化的使用执行的是构造,而不是赋值。这是语法有点令人困惑。A a3(a2),这[本质上]等效,在这方面会更清楚。

于 2013-10-27T01:19:11.953 回答
0

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

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

如果您将const限定符添加到您的复制 ctor/assign 方法中,您可能会看到您期望的结果。

于 2013-10-27T03:07:51.457 回答