Copy Constructor Assignment Operator Private Investigator

The copy constructor is made private so a copy of the class object cannot be created using this private copy constructor resulting in error.

Uses the to create a new object. is derived from and it calls in its constructor, which is private to it wont compile either.

Here is the output on Ideone. It doesn't compile even on gcc.

Why it works on Visual studio?
The reason is a possible Return Value optimization by the visual C++ compiler which elides the copy constructor.

As per the C++ standard, 12.8 copying class objects section 15

When certain criteria are met, an implementation is allowed to omit the copy construction of a class object, even if the copy constructor and/or destructor for the object have side effects. In such cases, the implemen-tation treats the source and target of the omitted copy operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later of the times when the two objects would have been destroyed without the optimization.111)

See my answer here which cites the Standard and the example code in this regard.

Does not compile for the same reason that is private.

Does not compile because is private.

By making ctor and assignment private (or by declaring them as =delete in C++11) you disable copy.

The point here is WHERE you have to do that. To stay with your code, IAbstract is not an issue. (note that doing what you did, you assign the subobject to a2, loosing any reference to . Value assignment is not polymorphic)

The issue comes with . Copying a Derived into another may in fact share the data that may be not designed to be shared (there are two instances that may call in their destructor).

If that's the case, it is that must be non-copyable and not assignable. Of course, if you make private the copy in , since the default copy for needs it, will also be not copyable. But if you define your own without calling copy, you can still copy them.

The problem is in Derived, and the solution must stay into Derived: if it must be a dynamic-only object accessed only by pointers or references, it is Derived itself that must have

Essentially it is up to the designer of the Derived class (that should know how Derived works and how is managed) to decide what to do with assignment and copy.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *