I would advice against any kind of copy constructor if the class allocates any memory! Same with assignment operators. It's dangerous! The reason is that you have no way of returning any result value from a constructor or operator that would indicate if the copying process has been successful.
I'd rather recommend something like this:
1 2 3 4 5 6 7 8 9
class student
{
bool CopyFrom(const student& src)
{
// Copy all values here
// Also copy all your allocated memory here
// Check if new allocations were successful. If not, return false.
}
}
but can't you do this in the copy constructor? Fair enough, a compiler-generated copy ctor wont handle deep copy, but you can roll your own. You're implying you can't do a deep copy using a copy constructor?
You can do anything in a constructor, sure. The only thing you can't do is: Return a value that would indicate success or failure. That's why I recommend copy constructors (and overloaded assignment operators) only for classes/structs that don't allocate memory on the heap.
This might crash, if the required memory could not be allocated in obj2's copy constructor.
Use exceptions to report errors where appropriate, and write code that is safe in the face of exceptions.
As with all best practices there are cases when you should ditch exceptions: in real-time systems, when writing perfomance critical code which will be compiled on compilers which dos not support zero-cost exceptions, when supporting legacy code which did was not created with exception safety in mind.
I would advice against any kind of copy constructor if the class allocates any memory! Same with assignment operators. It's dangerous! The reason is that you have no way of returning any result value from a constructor or operator that would indicate if the copying process has been successful.