Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens (exactly) if you leave out the copy-constructor in a C++ class?

What happens (exactly) if you leave out the copy-constructor in a C++ class?

Is the class just memcpy'd or copied member wise?

like image 554
horstforst Avatar asked Feb 27 '11 15:02

horstforst


People also ask

What happens if there is no copy constructor?

If no user-defined copy constructors are provided for a class type (struct, class, or union), the compiler will always declare a copy constructor as a non-explicit inline public member of its class.

Is copy constructor necessary?

A user-defined copy constructor is generally needed when an object owns pointers or non-shareable references, such as to a file, in which case a destructor and an assignment operator should also be written (see Rule of three).

Why do we delete the copy constructor?

Copy constructor (and assignment) should be defined when ever the implicitly generated one violates any class invariant. It should be defined as deleted when it cannot be written in a way that wouldn't have undesirable or surprising behaviour.

What will happen when copy constructor makes equal to delete?

The copy constructor and copy-assignment operator are public but deleted. It is a compile-time error to define or call a deleted function. The intent is clear to anyone who understands =default and =delete . You don't have to understand the rules for automatic generation of special member functions.


2 Answers

The class is copied member-wise.

This means the copy constructors of all members are called.

like image 51
mmmmmmmm Avatar answered Oct 02 '22 07:10

mmmmmmmm


The default copy constructor is made mebmber wise.

The same member-wise approach is also used for creating an assignment operator; the assignment operator however is not created if the class has reference members (because it's impossible to rebind a reference after construction).

like image 22
6502 Avatar answered Oct 02 '22 08:10

6502