0

I was wondering what does the delete keyword do in C++. I've seen someone delete the constructor function/method of a class like this:

Foo()=delete;

What does this (keyword) do and when/how can I use it?

Serket
  • 3,785
  • 3
  • 14
  • 45
  • It prohibits the use of that specific function. A use case could be that in a codebase I want all devs to use the new function `Foo2()` and I add `Foo()=delete;` – dejoma Jul 08 '20 at 12:11
  • 1
    @dejoma that is misleading, if you want that the function `Foo()` can't be used anymore and `Foo2` should be used instead then you just remove it. `= delete` is used if you want to e.g. remove a member function that would exist otherwise (e.g. because it is created by default, or would exist due to inheritance). Or if you want to prevent that automatic type conversation is utilized (e.g. `void foo(long long l) {} void foo(long l) = delete;` so in that case `foo(2L)` would not compile) – t.niese Jul 08 '20 at 12:55
  • @t.niese it could be used for a free function to get a compiler error instead of a linker error when the declaration should stay, though I've never seen this nor would I use it that way. Indeed a bit misleading – 463035818_is_not_an_ai Jul 08 '20 at 13:04
  • @idclev463035818 just removing the definition, and keeping the declaration would be indeed a bad idea. With `delete` you would have a `error: use of deleted function` instead of a `error: '…' was not declared in this scope` which you would get if you remove the declaration and definition. So yes one could think about using this for a more expressive compiler message. But that's not the main purpose. And since `[[deprecated]]` exists it is questionable if you want to do first a `[[deprecated]]` and then a `= delete` in the removal process. – t.niese Jul 08 '20 at 13:17

0 Answers0