penguru penguru - 11 months ago 38
C++ Question

When do we have to use copy constructors?

As I know that C++ compiler creates a copy constructor for each class. In which cases we have to write user defined copy constructors? Can you give some examples?


The copy constructor generated by the compiler does member-wise copying. Sometimes that is not sufficient. For example:

class Class {
    Class( const char* str );
    char* stored;

Class::Class( const char* str )
    stored = new char[srtlen( str ) + 1 ];
    strcpy( stored, str );

    delete[] stored;

in this case member-wise copying of stored member will not duplicate the buffer (only the pointer will be copied), so the first to be destroyed copy sharing the buffer will call delete[] successfully and the second will run into undefined behavior. You need deep copying copy constructor (and assignment operator as well).

Class::Class( const Class& another )
    stored = new char[strlen(another.stored) + 1];
    strcpy( stored, another.stored );

void Class::operator = ( const Class& another )
    char* temp = new char[strlen(another.stored) + 1];
    strcpy( temp, another.stored);
    delete[] stored;
    stored = temp;