When do we have to write a user-defined copy constructor?
c++, copy-constructor
Solution
The copy constructor generated by the compiler does member-wise copying. Sometimes that is not sufficient. For example:
class Class {
public:
Class( const char* str );
~Class();
private:
char* stored;
};
Class::Class( const char* str )
{
stored = new char[srtlen( str ) + 1 ];
strcpy( stored, str );
}
Class::~Class()
{
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;
}
Problem
I know that C++ compiler creates a copy constructor for a class. In which case do we have to write a user-defined copy constructor? Can you give some examples?
Related problems
- What does "default" mean after a class' function declaration?
- What is the copy-and-swap idiom?
- What is copy elision and how does it optimize the copy-and-swap idiom?
- Is it possible to write a common function that handles both the copy constructor and copy assignment operator?
- Dynamically allocating an array of objects
- I defined a non-copy constructor; will a copy constructor still be implicitly defined?
- What are your favorite C++ Coding Style idioms