c++ 如何限制一个类对象实例只建立在堆上、或只建立在栈上

#include<iostream>
#include <cstring>
using namespace std;

//new运算符:
//(1)执行operator new()函数,在堆空间中搜索何时的内存并进行分配。
//(2)调用构造函数构造对象,初始化这片内存空间。

//如何限制一个类对象只能建立在堆上?
//也就是不能创建在栈上,把构造函数设置为私有。但是new运算符就无法使用构造功能,无法使用。
//编译器在为类对象分配栈空间时,会检查析构函数的访问性。当析构函数是私有时,就不会栈上进行空间分配了。
//设置为私有的一个缺点就是,无法解决继承问题。
//因此,将析构函数设为protected可以有效解决这个问题,类外无法访问protected成员,子类则可以访问。
class A
{
    public:
        A(){}
    protected:          
        ~A(){}
};

//如何限制只能建立在栈上?
//把operator new()和operator delete()设置为私有
class B
{
    private:
        void* operator new(size_t t){}
        void operator delete(void* ptr){}
    public:
        B(){}
        ~B(){}
};


int main()
{
     A *a = new A();
     B b;
}


猜你喜欢

转载自blog.csdn.net/qq_36748278/article/details/80498151
今日推荐