如何限制对象只能建立在堆上或者栈上

类的建立一般是有两种方式。

1.静态建立方式 A a1; 栈上分配内存,然后调用构造函数,直接调用了类的构造函数。
2.动态建立方式 A* p=new A; 使用new运算符将对象建立在堆空间中,a.首先调用operator new函数,在堆上进行分配 b.调用构造函数构造对象。间接调用类的构造函数。

1.只建立在堆上

保证不能使用静态建立方式。不能直接调用类的构造函数

将构造函数设为私有,不可以的。
将析构函数设为私有,protected即可,可以。然后提供一个函数去析构。

class A
{
public:
    A(){}
    void destory(){delete this;}
protected:
    ~A(){}
};

//统一操作
class A
{
protected:
    A(){}
    ~A(){}
public:
    static A* create()
    {
        return new A();
    }
    void destory()
    {
        delete this;
    }
};

2.只建立在栈上

将new禁用,使operator new operator delete变成private.

class A
{
private:
    void* operator new(size_t t){}     // 注意函数的第一个参数和返回值都是固定的
    void operator delete(void* ptr){} // 重载了new就需要重载delete
public:
    A(){}
    ~A(){}
};

test code

#include<iostream>
using namespace std;
class A1
{
public:
    A1() {}
    void destory() { cout << "destory1"; delete this; }
private:
    ~A1() { cout << "~A1"; }
};

class A2
{
protected:
    A2() {}
    ~A2() {}
public:
    static A2* create()
    {
        return new A2();
    }
    void destory()
    {
        delete this;
    }
};

class A3
{
private:
    void* operator new(size_t t) {}     // 注意函数的第一个参数和返回值都是固定的
    void operator delete(void* ptr) {} // 重载了new就需要重载delete
public:
    A3() {}
    ~A3() {}
};

int main() {
    A1* a = new A1;
    a->destory();
    //A1 a1;//error
    A2* a2 =A2::create();
    a2->destory();

    A3 a3;
    //A3 a4 = new A3;//error
    return 0;
}

引自:https://blog.csdn.net/szchtx/article/details/12000867

posted @   风早&爽子  阅读(128)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示