Kurospidey
Kurospidey

Reputation: 423

Copy constructors in object initialization

Theoretical doubt here. Reading a book, and given this statement: StringBad metoo = knot; where:

the author says the following regarding copy constructors:

implementations have the option of handling this statement in two steps: using the copy constructor to create a temporary object and then using assignment to copy the values to the new object.That is, initialization always invokes a copy constructor, and forms using the = operator may also invoke an assignment operator.

My implementation do this in one step:

I could understand that other implementations could do it in two steps like this:

But the author says an initialization always invokes a copy constructor. Is that correct? If so, what are the steps the compiler would follow in some implementations to make it in two steps? I couldn't test it in mine cause, as I said it does it in one step.

Upvotes: 0

Views: 487

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477040

The author is wrong. What you have is a declaration statement with copy initialization, and the only way this can be realized is by instantiating a new object via the StringBad(StringBad const &) copy constructor.* The assignment operator will never be called in this situation, and doesn't even need to exist or be accessible.

There is almost no difference between the two variants StringBad metoo = knot; and StringBad metoo(knot);.

*) or the non-const version if that happens to exist and match.

Upvotes: 2

Related Questions