Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 usage of delete specifier vs private functions

Tags:

c++

c++11

I am in the process of boning up on my C++ (as in, attempting to get into more modern-style coding) and am looking at the delete specifier. It is my understanding that it is used to make sure that certain functionality cannot be defined or called. If I understand it correctly, this is primarily within the domain of assignment and copy. I am not quite sure what the difference is between using the delete specifier and just making those functions private.

For instance, what is the difference between:

 class Foo {
 private:
      Foo& operator(const Foo&);
      Foo(const Foo&);     
 };

And

 class Bar {
 public:
      Bar& operator(const Bar&) = delete;
      Bar(const Bar&) = delete;
 };

In other words: what does using the delete specifier gain? Is it just to make things look nicer?

like image 558
basil Avatar asked Mar 09 '17 17:03

basil


People also ask

Will delete operator works for normal function?

= delete can be used for any function, in which case it is explicitly marked as deleted and any use results in a compiler error.

What does delete keyword do when applied on a function declaration?

Using the delete operator on an object deallocates its memory.

Will delete operator works for normal function in C++?

Prior to C++ 11, the operator delete had only one purpose, to deallocate a memory that has been allocated dynamically. The C++ 11 standard introduced another use of this operator, which is: To disable the usage of a member function.

What does delete [] mean in C++?

Delete is an operator that is used to destroy array and non-array(pointer) objects which are created by new expression. Delete can be used by either using Delete operator or Delete [ ] operator. New operator is used for dynamic memory allocation which puts variables on heap memory.


1 Answers

One obvious difference is that if you make the function private, then it is still accessible from within the class and any friends.

An explicitly deleted function is not usable anywhere, so you know simply from that one line that it's never used, without having to inspect the implementation.

You can make the function both private and deleted: then its participation in overload resolution is more consistent.

like image 197
Toby Speight Avatar answered Sep 30 '22 15:09

Toby Speight