C++子结构间接自杀实验

之前在写一个TCP/UDP通信程序的时候,

我想试验这样一个结构:


子结构通过父结构的的STL函数间接自杀。。

结果当时得出了一个结论,是可行的。

后来又在其他平台上报错,总之各种危险,以后还是不要写这种跟编译器、平台相关的危险代码。


后来的经验是,对于STL里的类实例(或者大STRUCT)最好都用指针统一管理。具体管理方法我将会另外写篇经验心得。


附上代码:

 

//为了试验在子结构中能否通过调用父结构的STL函数删除自身
//结论:能!

//补充,某些时候不能……找不到原因,该方法最好不要使用


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Son;

bool KillId( Son const& instance );
int idtokill;

class Father
{
public:
	vector<Son> sons;

	void Kill( int id )
	{
		idtokill = id;
		sons.erase( remove_if(sons.begin(),sons.end(),KillId), sons.end());
	}
};

class Son
{
public:
	Son( Father* f, int id )
	{
		p_Father = f;
		m_id = id;
	}

	~Son()
	{
		//cout<<m_id<<"has been killed"<<endl;
	}

	void Kill()
	{
		p_Father->Kill( m_id );
	}

	Father* p_Father;
	int m_id;
};

bool KillId( Son const& instance )
{
	return instance.m_id == idtokill;
}

void main()
{
	Father f;
	Son s( &f, f.sons.size() );
	f.sons.push_back( s );

	Son s2( &f, f.sons.size() );
	f.sons.push_back( s2 );

	f.sons[0].Kill();
	cout<<f.sons.size()<<endl;
	f.sons[0].Kill();

	cout<<f.sons.size()<<endl;

	
	system("pause");
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值