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

后端 未结 6 1028
孤城傲影
孤城傲影 2020-11-30 03:44

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

6条回答
  •  醉话见心
    2020-11-30 04:08

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

提交回复
热议问题