今天七夕,群友让我帮忙给他分配一个对象,于是我。。。

今天七夕,群友让我帮忙给他分配一个对象,于是我只好尝试给他分配对象了:

cpp 复制代码
CGirlFrined *pGF = new CGirlFrined("大屌萌妹");

int nRet = (群友).SetGirlFriend(pGF);

if (nRet != 0)
{
    alert("分配失败!");
}

后来觉得这段代码过于简单,分配的方法也有些过于简单了,于是我参考了网上的代码,然后丰富了代码内容,包含NTR在内的更多的分配方式:

cpp 复制代码
#include <iostream>
#include <list>

using namespace std;

class CGirlFriend {
public:
	string name;
	int age;
	CGirlFriend() {
		this->name = "小萝莉";
		this->age = 0;
	}
	CGirlFriend(const string& name, int age = 12)
		: name(name), age(age)
	{}

	static void* operator new(size_t size){       
		cout << "女朋友准备中。。。" << endl;
	return malloc(size);
	}

		static void* operator new(size_t size, CGirlFriend* ptr){    
		cout << "NTR别人的女朋友。。。" << endl;
	return ptr;
	}

		static void* operator new[](size_t size) {     
		cout << "一大波女朋友准备中。。。" << endl;
		return malloc(size);
	}

		static void* operator new[](size_t size, list<void*>& lt) {    

		cout << "女朋友们的聚会准备中。。。" << endl;
		void* tmp = malloc(size);
		lt.push_back(tmp);
		return tmp;
	}
};


int main(void)
{

	CGirlFriend* gf1 = new CGirlFriend("小萝莉");

	CGirlFriend* gf2 = new(gf1) CGirlFriend;

	delete gf2;

	CGirlFriend* gfs = new CGirlFriend[10]{ { "萌妹子", 19 } };

	for (int i = 0; i < 10; ++i)
		cout << (gfs + i)->name.c_str() << endl;

	delete[] gfs;

	list<void*> girlList;

	CGirlFriend* gfss1 = new (girlList) CGirlFriend[10];
	for (int i = 0; i < 10; ++i)
		cout << (gfss1 + i)->name.c_str() << endl;

	CGirlFriend* gfss2 = new (girlList) CGirlFriend[20];

	for (auto& ptr : girlList)
		delete[] ptr;

	system("pause");

	return 0;

}

此代码在vs2015上测试运行通过,结果如下:

欢迎交流与讨论。

相关推荐
感哥18 小时前
C++ 面向对象
c++
沐怡旸20 小时前
【底层机制】std::shared_ptr解决的痛点?是什么?如何实现?如何正确用?
c++·面试
感哥1 天前
C++ STL 常用算法
c++
saltymilk2 天前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥2 天前
C++ lambda 匿名函数
c++
沐怡旸2 天前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥2 天前
C++ 内存管理
c++
博笙困了2 天前
AcWing学习——双指针算法
c++·算法
感哥2 天前
C++ 指针和引用
c++
感哥3 天前
C++ 多态
c++