This is a general question that I've been asking for a while but couldn't get a clear answer to. Do I need to code a copy constructor for a class when all instance data fields in this class are standard built in C++ data types?
Answer
The types of the member variables is not important for that(1), their semantics are. The rule is simple:
If you don't provide a copy constructor, the compiler will try to generate one for you. This default-generated one will perform the default copy operation on all member variables. For class types, this means calling the copy constructor. For primitive types, this means a bitwise copy.
If the default-generated constructor does what you need, don't declare your own. If it wouldn't do what you need, declare one yourself. It is possible to create a class with non-primitive member variables and perfectly OK default copy semantics:
struct PersonId
{
std::string surname;
std::vector givenNames;
};
Likewise, it is possible to create a class with primitive-type member variables where the default copy semantics would not be OK:
class UniqueNamed
{
int id;
UniqueNamed() : id(0) {}
public:
UniqueNamed(const UniqueNamed &src) : id(src.id + 1) {}
int getId() const { return id; }
static UniqueNamed initial;
};
So it depends on the class's semantics, not on the types of its data members.
This touches the general concept of the semantics of copying, moving & wonership, and their implementations in C++. You might want to read something about the rules of zero, three, and five.
(1) Of course, if any member variable is of a non-copyable type, and you want your class to be copyable, you have to provide the copy constructor yourself, as the default-declared one would be defined as deleted.
No comments:
Post a Comment