質問

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

  • StringBad is a class
  • knot is an object of that class

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:

  • Creates the metoo object with the copy constructor, the same as this : StringBad metoo(knot);

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

  • Create a metoo object with the default constructor, like : StringBad metoo;
  • Use the overloaded asignment operator to assign the knot object to the metoo object.

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.

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top