Implement a class that can only generate objects on the stack

analyze

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

  Method 1: The construction of a class object is realized by the constructor. If the constructor is declared as a private or protected type, the constructor cannot be called outside the class, and the object cannot be new outside the class. But this also cannot define objects outside the class. In this regard, we can define a public interface in the class to return the object generated by the member function, and then when defining the class outside the class, we only need to call this function, but this has drawbacks, because outside the class, only the class can be used object to call this member function, so this interface should be declared static.

  Method 2: Only declare operator new and operator delete without defining them. When a new object is called, operator new and construction will be called at the same time, and operator new is only declared and defined, resulting in the failure of new an object. But this method has a flaw, that is, it cannot prevent objects from being defined in the static area.

accomplish

//方法一
class AA
{
private:
    AA(int aa = 0)
        :_aa(aa)
    {}
public:
    static AA GetAAOBj()
    {
        return AA();
    }
protected:
    int _aa;
};

int main()
{
    AA aa = AA::GetAAOBj();
    return 0;
}
//方法二
class AA
{
private:
    void* operator new(size_t size);
    void operator delete(void* p);
protected:
    int _aa;
};

AA aa;     //此方法的缺陷在于防止不了在静态区定义对象

int main()
{
    //AA* p = new AA;   //失败(operator new+构造)
    AA aa;
    return 0;
}

Guess you like

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