问题描述:

C++ will create copy constructor and copy assignment operator for class. My questions is why it is creating two member function ? What is the significance and what is the difference by copying the object by copy constructor and copy assignment operator? Thank you in advance.

网友答案:

Copy assignment and copy construction do different things. Copy assignment has to take a fully constructed object and change it, while copy construction has to take a non-fully constructed object and do that initial construction.

For example copy assignment on a class that manages a resource has to ensure that its old resource is properly disposed of after it has taken ownership of the 'copied' resource, whereas the copy constructor doesn't have any previous resource to deal with.

网友答案:

If you have pointers as data members in your class, and if they are directly getting copied to another object, more than one object will access that pointer memory (unintentionally). To avoid that we can override copy constructor/assignment operator.

If you do not override these two functions, compiler copies bit by bit to another object.

相关阅读:
Top