What is the use of "= delete" in the declaration of a constructor in C++?

Asked

Viewed 170 times

15

I came across a builder declared as follows:

State(const State& em) = delete;

Does anyone know what the = delete at the end of the signature of the manufacturer?

  • I’ve never seen that. It has more context?

  • Worse than not, it is only asked to implement the copy builder and is given this signature.

1 answer

14


By default C++ creates the copy and assignment constructs (move) for you with a standard code. If you want the class not to have these constructors you need to inform the compiler that it should be "deleted", so any attempt to call these constructors will give error.

Contrary to what it seems you are not creating a builder, you are prohibiting its creation.

This has been going on since C++11. If you’d thought about it better you’d probably be opt-in and not opt-out as it had to be for compatibility reasons. At first no one thought that there could be a class without this constructor.

It became interesting to prohibit the copy builder and leave only the assignment one working which is much more efficient, where it fits.

If some place has implemented the copy constructor and ordered it to do so, there is something weird. This is the opposite of implementing.

  • I get it, so basically I’m saying that the State object is not going to have a copy builder...

  • @Jonathan Strabucobelotti this.

  • Good answer. It is important to remember that even if the constructor is marked as deleted, it still participates in overload resolution (Overload Resolution), then the declaration still exists, but if this constructor is selected by resolution, then the ban occurs.

  • @Márioferoldi is true.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.