c++c++-faq

Is it possible to prevent stack allocation of an object and only allow it to be instantiated with 'new'?


Is it possible to prevent stack allocation of an object and only allow it to be instiated with 'new' on the heap?


Solution

  • One way you could do this would be to make the constructors private and only allow construction through a static method that returns a pointer. For example:

    class Foo
    {
    public:
        ~Foo();
        static Foo* createFoo()
        {
            return new Foo();
        }
    private:
        Foo();
        Foo(const Foo&);
        Foo& operator=(const Foo&);
    };