4

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
user3366592
  • 439
  • 7
  • 23

1 Answers1

3

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{}); }
};
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455