2

The class A is declare as follow:

class A {
public:
    A() {
        cout<<"A()"<<'\n';
    }
    A(int i) {
        cout<<"A(int i)"<<'\n';
    }
    A(const A& a_) {
        cout<<"A(const A& a_)"<<'\n';
    }
};

When I initialize 'A' by an integer with equal operator:

int main() {
    A a = 123;
    return 0
}

Then it only output: A(int i) so I guess it only invoke A::A(int i) and the copy constructor is never used in this situation.

But when I declare A::A(const A& a_) = delete, the codes as follow:

class A {
public:
    A() {
        cout<<"A()"<<'\n';
    }
    A(int i) {
        cout<<"A(int i)"<<'\n';
    }
    A(const A& a_) = delete;
};
int main() {
    A a = 123;
    return 0;
}

The compiler issues an error:

Copying variable of type 'A' invokes deleted constructor.

So my question is: Why the copy constructor can't be deleted even it's not invoked in this situation?

whoisraibolt
  • 2,082
  • 3
  • 22
  • 45
yoyo
  • 31
  • 5
  • The copy-constructor is elided in the first case, which is why you only see a call to `A(int)` but even if it is elided, it must be available (until C++17) which is why deleting it makes your code ill-formed. The two duplicate links explain this in more depth. – Holt May 27 '19 at 14:54
  • Get it, thank you very much! – yoyo May 28 '19 at 01:06
  • Do you mean that if compiler don't optimize the code, the executable file compiled from the code will invoke **A(int)** to create a temporary variable and then invoke copy constructor to initialize **'a'** by the temporary variable just created? – yoyo May 28 '19 at 08:14
  • Yes, until C++17. If you are using g++ or clang, you can pass the option `-fno-elide-constructors` to see this: https://godbolt.org/z/3IhPBm If you look at the generated assembly with `-fno-elide-constructors`, you'll notice a call to `A(int)` and a call to `A(const& A)`. Without the option, you get a single call to `A(int)` because the copy-constructor is elided. If you set `-std=c++17`, you will see only one call even with `-fno-elide-constructors` because copy-elision is guaranteed in such case since C++17. – Holt May 28 '19 at 08:19
  • Ok, I get it, you are very nice, thank you! – yoyo May 28 '19 at 12:11

0 Answers0