本文总结C++ 中的内存管理,总结如下
【1】尽量用share_ptr管理资源(Efective C++条款13:以对象管理资源)
shared_ptr (C++ Primer)自动销毁所管理的对象:
有层含义:
1、一个shared_ptr的实例引用计数为0时,shared_ptr类自动销毁此对象。
{ ...
shared_ptr<int> sp(new(10)) //sp 指向一个int 型,值为10的地址。
...
} //sp 离开此作用域时,sp本身会被销毁
2、调用所指对象的析构函数,执行资源回收。(注意:默认析构函数也会进行资源回收,但是他只回收栈空间,不回收堆空间)
class Son{
public:
int x;
int y;
Son(int x_, int y_){
cout << "constructor of son"<< endl;
this->x = x_;
this->y = y_;
}
~Son(){
cout << "dis con of Son"<< endl;}
};
class Base{
public:
int a ;
Son * point; //point 本身在栈空间,但是它指向的内存在堆空间
Base(int a_, int x_, int y_){
point = new Son(x_, y_);
this->a = a_;