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
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{}); }
};