Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the accessibility of deleted constructors/operators matter?

Tags:

c++

c++11

If a type has its default member(s)s deleted, does it make a difference what the accessibility of the declaration is?

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

class FooB {
private:
  FooB() = delete;
  FooB(FooB const&) = delete;
  FooB& operator=(FooB const&) = delete;
}

class FooC {
protected:
  FooC() = delete;
  FooC(FooC const&) = delete;
  FooC& operator=(FooC const&) = delete;
}
like image 689
Drew Noakes Avatar asked Feb 03 '14 22:02

Drew Noakes


People also ask

What will happen when copy constructor makes equal to delete?

The copy constructor and copy-assignment operator are public but deleted. It is a compile-time error to define or call a deleted function. The intent is clear to anyone who understands =default and =delete . You don't have to understand the rules for automatic generation of special member functions.

What does use of deleted function mean?

It means the compiler should immediately stop compiling and complain "this function is deleted" once the user use such function. If you see this error, you should check the function declaration for =delete .

Can default constructor be deleted?

If no user-defined constructors are present and the implicitly-declared default constructor is not trivial, the user may still inhibit the automatic generation of an implicitly-defined default constructor by the compiler with the keyword delete.

Can we delete constructor in C++?

We can also use = delete to specify that you don't want the compiler to generate that function automatically. In another way, = delete means that the compiler will not generate those constructors when declared and this is only allowed on copy constructor and assignment operator.


2 Answers

Though accessibility and deletedness are orthogonal, it's hard to see how there could be a practical difference in the case you propose.

like image 87
Lightness Races in Orbit Avatar answered Oct 21 '22 06:10

Lightness Races in Orbit


Might be artificial, but it does make a little difference

class FooA {
private:
  FooA& operator=(FooA const&) = delete;
};

class FooB : FooA {
  // ill-formed because FooB has no access
  using FooA::operator=;  
};

Whether it's a practical difference... I don't really know. If FooA is a template parameter and you say using T::BazBang, it might happen in practice.

like image 32
Johannes Schaub - litb Avatar answered Oct 21 '22 05:10

Johannes Schaub - litb