C++ 只能new / 只能定义 的方式生成新对象

// new_delete.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;
// 只能定义,不能new : 把new的重载私有或者保护
class A{
public:
	A(){
		cout << "A()" << endl;
	}
	~A(){
		cout << "~A()" << endl;
	}
private:
	void* operator new(size_t size)
	{
		cout << "operator new" << endl;
		return nullptr;
	}
};

// 只能new 不能定义 : 把类的析构私有或者保护
class B{
public:
	B(){
		cout << "B()" << endl;
	}
	//void* operator new(size_t size)
	//{
	//	cout << "B operator new" << endl;
	//	return nullptr;
	//}
	void release(){
		cout << "B release" << endl;
		delete this;
	}
protected:
	~B(){
		cout << "~B()" << endl;
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	A a0;
	//A* a1 = new A; // error

	//B b0; // error
	B* b1 = new B;
	//delete b1; error
	b1->release();
	return 0;
}


版权声明:本文为ustb_atrx原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。