如何禁止类对象在堆或者栈上分配内存

一:禁止在堆上分配内存

#include <iostream>
#include <list>
#include <map>
#include <mutex>
using namespace std;

class A
{
    
    
private:
    static void* operator new(size_t size);
    static void operator delete(void* phead);
    static void* operator new[](size_t size);
    static void operator delete[](void* phead);
};


int main()
{
    
    
	/*检测内存泄漏*/
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

	/*如何强制类对象不可以或只可以在堆上分配内存
	只需要重载下new和delete运算符即可。
	*/
	A* p = new A(); //不可以
	A* q = new A[10]();//不可以

	delete p;
	delete[]q;

	A obj;//可以
	return 0;
}

二:禁止在栈上分配内存

#include <iostream>
#include <list>
#include <map>
#include <mutex>
using namespace std;

class A
{
    
    
public:
	void destroy()
	{
    
    
		delete this;
	}
	void destroysz()
	{
    
    
		delete[] this;
	}
private:
	~A() {
    
    }
	//A(){}
};

int main()
{
    
    
	/*检测内存泄漏*/
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    /*
    提高将构造函数或者析构函数设置为private
    */
	A obj; //不可以
	A* p = new A(); //可以
    A* q = new A[10]();//可以

	//delete p;//不可以
	//delete[]q;//不可以

	p->destroy();
	q->destroysz();
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38158479/article/details/120339104