Why and when to delete copy constructor and operator=
Asked Answered
M

2

6

Why it is useful to explicitly 'disable' or delete the = operator and copy constructor of a class:

SomeClass& operator=(SomeClass&) = delete;
SomeClass(SomeClass&) = delete;

I guess this makes sense if the class is a singleton. But are there any other situations? (Maybe this has something to do with performance issues?)

Millimeter answered 15/12, 2015 at 14:36 Comment(0)
M
7

This has nothing to do with performance. You disallow copying whenever it does not make sense to copy your class, i.e. if it is not clear what copying the class in question would mean.

Famous examples are the standard IO streams with their complex internal state and std::unique_ptr which can't be copied because, well, it is the unique pointer pointing to its managed object.

Mattah answered 15/12, 2015 at 14:42 Comment(2)
will there be default implementations if I don't explicitely specify one by myself?Millimeter
@Millimeter Under certain conditions, yes. For reference, see e.g. en.cppreference.com/w/cpp/language/copy_constructor. If you have questions about that, it would be grounds for a whole new question here on SO.Mattah
O
2

I think the following is a good addition::

If you want to disallow passing the object by value, you may delete them.

Orin answered 28/12, 2019 at 21:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.