之前在写一个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");
}