Why explicitly delete the constructor instead of making it private?

前端 未结 3 1717
既然无缘
既然无缘 2020-11-30 00:02

When/why would I want to explicitly delete my constructor? Assuming the reason is to prevent its usage, why not just make it private?

class Foo
         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 00:48

    why explicitly delete the constructor?

    Another reason:
    I use delete when I want to assure that a class is called with an initializer. I consider it as a very elegant way to achieve this without runtime checks.

    The C++ compiler does this check for you.

    class Foo
    {
       public:
           Foo() = delete;
           Foo(int bar) : m_bar(bar) {};
       private:
           int m_bar;
    }
    

    This - very simplified - code assures that there is no instantiation like this: Foo foo;

提交回复
热议问题