Search code examples
c++classc++17new-operator

Is there a way to disable a non-dynamic class constructor?


Imagine a class which can be constructed only with the new operator. Is it possible to achieve this in the c++17 standard without deleting its destructor?

class Foo
{
    Foo(){}
    ~Foo(){}
    // delete non-dynamic constructor...?
}

// ...
Foo A; // compiling error
Foo* B = new Foo(); // ok

Solution

  • You can easily do this by keeping all constructors private and wrapping the mandatory invocation of new in a factory function.

    You should also disable copying the class.

    class Foo
    {
    private:
      Foo() {}
      Foo(const Foo&) = delete;
      Foo& operator= (const Foo&) = delete;
    
    public:
      ~Foo() {}
    
      static std::unique_ptr<Foo> create() { return std::unique_ptr<Foo>(new Foo{}); }
    };