Implement a class that can only generate objects on the heap

analyze

  Objects can be generated on the stack or on the heap through new. If you only want objects to be generated on the heap, you need to start with the internal structure of the class.

  The construction of class objects is achieved through constructors. If the constructors are declared as private or protected types, the constructors cannot be called outside the class, and objects cannot be generated from the stack outside the class. But at the same time, you can't new out an object outside the class. In this regard, we can define a public interface in the class to return the object created by the member function new, and then when we define the class outside the class, we only need to call this function, but this has drawbacks, because outside the class only through object of the class to call this member function, so this interface should be declared static.

accomplish

class AA
{
private:
    AA(int aa = 0)
        :_aa(aa)
    {}
    //类的防拷贝
    //1.只声明不定义
    //2.声明成私有
    AA(const AA& aa);
public:
    static AA* GetAAObj()
    {
        return new AA;
    }
protected:
    int _aa;
};

int main()
{
    AA* p = AA::GetAAObj();
    //AA aa(*p);    //栈上定义的对象,若想要其定义失败,应使用类的防拷贝
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325573080&siteId=291194637