1

Define a class as follows:

class A {
public:
  A(): s("") {}                             //default constructor
  A(const char* pStr): s(pStr) {}           //constructor with parameter
  A(const A& a) : s(a.s) {}                 //copy constructor
  ~A() {}                                   //destructor
private:
  std::string s;
};

The code below will execute direct initialization:

A a1("Hello!");   //direct initialization by calling constructor with parameter
A a2(a1);          //direct initialization by calling copy constructor

And what follows will execute copy initialization:

A a3 = a1;  
A a4 = "Hello!";

To my understanding, A a4 = "Hello" is equivalent to:

//create a temporary object first, then "copy" this temporary object into a4 by calling copy constructor    
A temp("Hello!");    
A a4(temp);

So what is the difference between A a3 = a1 and A a2(a1)? It seems they both call copy constructor. And whether are my comments above right? (given no compiler optimization)

Finley
  • 795
  • 1
  • 8
  • 26

1 Answers1

0

There's a difference between direct-initialization and copy-initialization:

Copy-initialization is less permissive than direct-initialization: explicit constructors are not converting constructors and are not considered for copy-initialization.

So if you make the copy constructor explicit then A a3 = a1 won't work; while A a2(a1) still works fine.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Well, and is my understanding on case `A a4 = "Hello"` right without any compiler optimization? – Finley Jul 18 '18 at 02:11
  • @Finley Yes, it's right. With optimization, the copy constructor is usually optimized. – songyuanyao Jul 18 '18 at 02:12
  • @Finley Since C++17 `A a4 = "Hello";` is exactly the same as `A a4("Hello");`, other than the `explicit` check – M.M Jul 18 '18 at 04:42