Default Copy Constructor

B

Bob

Hi,

If a class contains only built-in types and standard library objects
such as strings and vectors, is it safe to let the compiler create the
copy constructor and assignment operator, or is it advised to always
write your own?

I know you need to write your own if there is any dynamic memory
allocation etc, but I was curious as to the "correct" way in the case
of static variables.

Thanks,
Bob.
 
J

John Carson

Bob said:
Hi,

If a class contains only built-in types and standard library objects
such as strings and vectors, is it safe to let the compiler create the
copy constructor and assignment operator
Yes.

or is it advised to always
write your own?

No. In fact it is safer to let the compiler do it since you might make a
mistake.

There are occasions when you might need to create your own versions (e.g.,
if you want to keep count of the number of objects created of a particular
class) but, unless you want to do something beyond mere construction or
assignment, the compiler-generated version is fine.
 
R

Rob Williscroft

Bob wrote in in
comp.lang.c++:
Hi,

If a class contains only built-in types and standard library objects
such as strings and vectors, is it safe to let the compiler create the
copy constructor and assignment operator, or is it advised to always
write your own?

The rule is quite simple:

If all members have constructors, assigment operator and destructor that
"do the right thing(tm)" then the compiler generated ctor's etc
will do the right thing.

Typically pointers that point to dynamic memory don't obey this rule.
Another example would be the FILE * returned by fopen (it needs to
be closed by fclose).

Most of the types defined by the C++ part of the standard library
do obey this rule, however ther are some oddity's:

I know you need to write your own if there is any dynamic memory
allocation etc, but I was curious as to the "correct" way in the case
of static variables.

static variables aren't part of an instance, they're globals (but globals
that are restricted to the classes scope) and don't need to be constructed
by the copy constructor or assigned to by the assignment operator.


Rob.
 
V

Victor Bazarov

John Carson said:

Well, to be technically correct, _pointers_ _are_ in fact built-in types,
but somehow I think the OP didn't mean pointers. In any case, mentioning
"The Rule of Three" could also help.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top