How To Limit Object Creation to Pointer only in C++

c++, pointers

Solution

You could make the constructor private and provide a `static` factory method that returns a dynamically allocated instance:

class A
{
public:
    static A* new_instance() { return new A(); }
private:
    A() {}
};

Instead of returning a raw pointer, consider returning a smart pointer instead:

class A
{
public:
    static std::shared_ptr<A> new_instance()
    {
        return std::make_shared<A>();
    }
private:
    A() {}
};

Problem

Considering class A, I would like to limit its creation to new. That is ``` A* a = new A; // Would be allowed. A a; // Would not be allowed. ``` How could this be accomplished?

Original source

Related problems