主要探讨对象的构造顺序与内存的布局,主要参考来源为《Exceptional C++ Style中文版》
文中第十四条 顺序!顺序!根据文中的代码摘录如下,代码中添加了一些调试的信息。
[cpp]
#include <map>
struct classcomp {
bool operator() (const __int64& lhs, const __int64& rhs) const
{return lhs<rhs;}
};
std::multimap<__int64,std::string,classcomp> m_Construtor;
class B1{
public:
B1()
{
std::cout<<"Constructor B1 "<<this<<'\n';
m_Construtor.insert(std::pair<__int64,std::string>((__int64)this,"Constructor B1 "));
}
virtual ~B1()
{
std::cout<<"Destructor B1 "<<this<<'\n';
}
};
class V1:public B1{
public:
V1()
{
std::cout<<"Constructor V1 "<<this<<'\n';
m_Construtor.insert(std::pair<__int64,std::string>((__int64)this,"Constructor V1 "));
}
virtual ~V1()
{
std::cout<<"Destructor V1 "<<this<<'\n';
}
};
class D1:virtual public V1{
public:
D1()
{
std::cout<<"Constructor D1 "<<this<<'\n';
m_Construtor.insert(std::pair<__int64,std::string>((__int64)this,"Constructor D1 "));
}
virtual ~D1()
{
std::cout<<"Destructor D1 "<<this<<'\n';
}
};
class B2{
public:
B2()
{
std::cout<<"Constructor B2 "<<this<<'\n';
m_Construtor.insert(std::pair<__int64,std::string>((__int64)this,"Constructor B2 "));
}
virtual ~B2()
{
std::cout<<"Destructor B2 "<<this<<'\n';
}
};
class B3{
public:
B3()
{
std::cout<<"Constructor B3 "<<this<<'\n';
m_Construtor.insert(std::pair<__int64,std::string>((__int64)this,"Constructor B3 "));
}
virtual ~B3()
{
std::cout<<"Destructor B3 "<<this<<'\n';
}
};
class V2:public B1,public B2{
public:
V2()
{
std::cout<<"Constructor V2 "<<this<<'\n';
m_Construtor.insert(std::pair<__int64,std::string>((__int64)this,"Constructor V2 "));
}
virtual ~V2()
{
std::cout<<"Destructor V2 "<<this<<'\n';
}
};
class D2:public B3,virtual public V2{
public:
D2()
{
std::cout<<"Constructor D2 "<<this<<'\n';
m_Construtor.insert(std::pair<__int64,std::string>((__int64)this,"Constructor D2 "));
}
virtual ~D2()
{
std::cout<<"Destructor D2 "<<this<<'\n';
}
};
class M1{
public:
M1()
{
std::cout<<"Constructor M1 "<<this<<'\n';
m_Construtor.insert(std::pair<__int64,std::string>((__int64)this,"Constructor M1 "));
}
virtual ~M1()
{
std::cout<<"Destructor M1 "<<this<<'\n';
}
};
class M2{
public:
M2()
{
std::cout<<"Constructor M2 "<<this<<'\n';
m_Construtor.insert(std::pair<__int64,std::string>((__int64)this,"Constructor M2 "));
}
virtual ~M2()
{
std::cout<<"Destructor M2 "<<this<<'\n';
}
};
class X:public D1,public D2
{
public:
X()
{
std::cout<<"Constructor X "<<this<<'\n';
m_Construtor.insert(std::pair<__int64,std::string>((__int64)this,"Constructor X "));
}
virtual ~X()
{
std::cout<<"Destructor X "<<this<<'\n';
}
private:
M1 _m1;
M2 _m2;
};
int _tmain(int argc, _TCHAR* argv[])