Difference in constructors with X () = delete; and private X ();
Suppose we have class X and want wo to explicitly disallow, say, the standard constructor. I've been using a header file for a long time:
private:
X(); // 1.
so that the constructor is disabled outside of the class, so for someone else. But I recently found out that the following is recommended in C ++ 11:
X() = delete; // 2.
Both will achieve my desire to disallow the default constructor.
But what is the difference between them? Why does C ++ 11 recommend the latter? Are there other flags, signals set in the 2. way?
source to share
Example 1 was the way to do it before we got it = delete
, which came out in C ++ 11. Now that we have it = delete
, this will get rid of the constructor entirely. When creating a private private constructor, you can still use that constructor in a member function, where if you try to put an object in a member function with by default = delete
, it will be a compiler error.
#include <iostream>
class Foo
{
Foo();
public:
static void SomeFunc() { Foo f; }
};
class Bar
{
public:
Bar() = delete;
static void SomeFunc() { Bar b; }
};
int main()
{
Foo::SomeFunc(); // will compile
Bar::SomeFunc(); // compiler error
}
source to share