Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete modifier vs declaring function as private

I read this question, but it still doesn't make a lot of sense to me. It still sounds more like a sugarcoating feature.

What's the difference between:

class A 
{
// public/private ?
    A (const A&) = delete; 
};

and

class A 
{
private:
    A (const A&); // MISSING implementation
};

Same for operator= or other functions.

like image 267
Kiril Kirov Avatar asked Sep 17 '13 10:09

Kiril Kirov


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 mean C++?

delete keyword 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.


2 Answers

One difference is that =delete allows for compile-time errors while in some cases the declaration without a definition is only caught at link-time (at which the error message is typically not pointing you to the source of the problem). One such case is when you add a member function that tries to copy an instance of A. Even when it's not a member function of A, the error message about the copy-ctor being private is not as clear as using =delete.

To avoid confusion, I'd recommend you make the deleted function public as otherwise you will get additional and misleading error messages.

like image 75
Daniel Frey Avatar answered Oct 14 '22 14:10

Daniel Frey


The difference is that the purpose of the =delete code is explicit in it's purpose. Declaring functions as private / inaccessible was a trick. Although most people knew it, the error it generated was obscure (a linking/access level error instead of a semantical problem in the code - i.e. "you are using a deleted function").

like image 45
utnapistim Avatar answered Oct 14 '22 13:10

utnapistim