Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the default assignment operator call operator= on all members?

And similarly, does the default copy constructor call the copy constructor on all members? For example, if a class has a non-POD member like so:

class A
{
    std::string str;
};

...will the default compiler-generated copy constructor and assignment operator work correctly? Will they call the string's copy constructor and operator= or will they just make a bitwise copy of member variable str?

In other words, does having a std::string member mean this class needs a user-implemented copy constructor and assignment operator?

like image 730
bythescruff Avatar asked Sep 27 '12 08:09

bythescruff


1 Answers

Yes, the compiler-generated one will work correctly.

However, if you implement your own and leave them empty, it won't.

If you're not managing memory and all your members provide correct copying/assignment/destruction, you don't need (and shouldn't) implement your own copy constructor/destructor/assignment operator.

In other words, does having a std::string member mean this class needs a user-implemented copy constructor and assignment operator?

No, the compiler-generated ones will work perfectly.

like image 96
Luchian Grigore Avatar answered Oct 29 '22 17:10

Luchian Grigore