Copy Constructor in C++ is called when object is returned from a function?

送分小仙女□ 提交于 2019-11-28 04:23:36

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.

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.

xtofl

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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!