vendredi 26 février 2021

When should we write our own move constructor (move assignment operator)

A user-defined move constructor and move assignment operator could have been omitted in all examples explaining move semantics I have seen so far because compilers generated ones will do the job.

The answers I found in stackoverflow will not go beyond the "Rule of three" (Rule of five) - so if a class defines any of the following then it should probably explicitly define all five.

But for copy constructor and all other members the reason is obvious and an example could be written easily to show what issues can occur if user-defined copy constructor doesn't exist.

In wikipedia we can find:

A user-defined copy constructor is generally needed when an object owns pointers or non-shareable references, such as to a file.

So the question is if there are examples that will show if user-defined move constructor or move assignment operator are really needed or I can assume that in 99% of cases compiler generated ones will be enough.

Aucun commentaire:

Enregistrer un commentaire