Question

I understand copy constructor is called on three instances

  1. When instantiating one object and initializing it with values from another object.
  2. When passing an object by value.

3. When an object is returned from a function by value.

I have question with no.3 if copy constructor is called when an object value is returned, shouldn't it create problems if object is declared locally in the function.

i mean the copy constructor is a deep copy one and takes reference of an object as parameter

Was it helpful?

Solution

It's called exactly to avoid problems. A new object serving as result is initialized from the locally-defined object, then the locally defined object is destroyed.

In case of deep-copy user-defined constructor it's all the same. First storage is allocated for the object that will serve as result, then the copy constructor is called. It uses the passed reference to access the locally-defined object and copy what's necessary to the new object.

OTHER TIPS

The copy is done before the called function exits, and copies the then-existing local variable into the return value.

The called function has access to the memory the return value will occupy, even though that memory is not "in scope" when the copy is being made, it's still available.

According to an answer to my question, the copy constructor may be called even twice: once to copy a local object onto the return 'object', and once to copy the return object onto the variable it was assigned to.

However, it needn't be! The compiler can optimize both copy constructions away.

No, it calls it before the locals are destroyed. You can test this with an object that logs destruction and copy construction, or by looking at the generated assembly code.

There are three general cases where the copy constructor is called:

  1. When instantiating one object and initializing it with values from another object (of same type).
  2. When passing an object by value.
  3. When an object is returned from a function by value.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top