class A{
int a=5;
public:
A(){ cout << "default construct A" << endl; }
~A(){ cout << "destroy A" << endl; }
};
class B{
private:
A a;
public:
B(){ cout << "default construct B" << endl; }
~B(){ cout << "destroy B" << endl; }
int a=5;
public:
A(){ cout << "default construct A" << endl; }
~A(){ cout << "destroy A" << endl; }
};
class B{
private:
A a;
public:
B(){ cout << "default construct B" << endl; }
~B(){ cout << "destroy B" << endl; }
};
int _tmain(int argc, _TCHAR* argv[])
{
auto p = new B();
delete p;
}
过程:
先创建 A
再创建 B
delete p;
过程分解:
1.先调用 B 的 析构函数
然后再调用 A 的析构函数
2.然后才会将内存中数据释放掉
领悟:boost::shared_ptr<> 中将px所指向的内存释放工作交给 shared_count pn去处理。而boost::shared_ptr采用的是默认的析构函数。
分析:shared_ptr 对象释放,必定会调用 shared_ptr 的析构函数 和 shared_count的析构函数,将 px指向的内存释放工作交由 shared_count来处理(通过处于这个过程中)
std::shared_ptr 的实现略有不同
boost::shared_ptr<> 采用的是 类的组合
std::shared_ptr<> 采用的是类的继承