Copy and move constructors are
constructors. What is the purpose of a constructor? To initialize object when it is created. User defined types have constructors. User defined types are classes. You can't redefine "constructor" of simple type, like
double
.
RAII (Resource Acquisition Is Initialization) is a programming idiom that is often recommended for C++, Java, and C#. The important point is that variables are assigned
known value already when they are created.
Have you seen "linked list" examples? Many have a bit like this:
1 2 3 4
|
Node* p = new Node;
p->data = data;
p->next = root;
root = p;
|
However, the Node is a user defined type and can have custom constructor.
With help of such the above could be written:
root = new Node( data, root );
This part of code is simpler, because the
p->data = data; p->next = root;
is neatly in constructor.
The copy and move constructors initialize the new object with value of same type. Since such copying is very common, compiler generates them automatically, except in certain special cases. That version is just a simple "shallow copy".
1 2 3 4 5
|
int x = 42;
int* y = &x;
int* z = y;
int* w = new int {*y};
delete w;
|
Both z and y point to x. You can modify value of x via both pointers. The z is a "shallow copy".
The w does not point to x. It points to a different
int
that also has 42 as initial value. The w is a "deep copy", because also the pointed to object is a distinct copy.
You need to implement copy and/or move constructors only if your class is such that the default shallow copy is not appropriate.
The difference between "copy" and "move" is that if you move construct, the original is not kept intact; the move is just an optimization for situation, where you have to create a copy but don't actually need the original after that.
Modern C++ has in its Standard Library many custom types and functions. When you use them, you don't need to have pointers in your code explicitly. Those custom types probably do have pointers internally, do have custom copy and move constructors, and so forth, but we don't have to worry about those details.
Is it good to understand pointers? Yes.
Are they beginner material? Not in modern C++.