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

后端 未结 6 1022
孤城傲影
孤城傲影 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:03

    You could create a header file that provides an abstract interface for the object, and factory functions that return pointers to objects created on the heap.

    // Header file
    
    class IAbstract
    {
        virtual void AbstractMethod() = 0;
    
    public:
        virtual ~IAbstract();
    };
    
    IAbstract* CreateSubClassA();
    IAbstract* CreateSubClassB();
    
    // Source file
    
    class SubClassA : public IAbstract
    {
        void AbstractMethod() {}
    };
    
    class SubClassB : public IAbstract
    {
        void AbstractMethod() {}
    };
    
    IAbstract* CreateSubClassA()
    {
        return new SubClassA;
    }
    
    IAbstract* CreateSubClassB()
    {
        return new SubClassB;
    }
    

提交回复
热议问题