条款13 以对象管理资源
在C++中 我们申请资源(new) 之后需要手动释放资源(delete)
Test* t = new Test();//申请资源
..
..
..
delete t;//释放资源
但是我们不知道
…
…
…
在申请和释放中间是否会发生什么匪夷所思的事情使得程序提前终止未能执行delete。[异常,goto,return]
如果申请的资源未被释放就会造成内存泄漏
Test* t = GetText("t");
return;
delete t;
为了解决这个问题,神奇的智能指针出现了!!!!
auto_ptr
你只需要把类丢进智能指针他就会自动帮你释放资源。
auto_ptr<Test> t2(GetText("t2"));
//不需要delete他会自动delete
其实自动delete的机制就是对象是由栈存储的所以会自动释放内存的机制
智能指针实质是一个对象,行为表现的却像一个指针。
假设有个A类,你创建这个对象,生命周期结束他会自动释放掉
A a;
一次性说太大我怕消化不了。先看看代码
#include <iostream>
#include<string>
using namespace std;
class Test
{
public:
Test(string test) :test(test)
{
cout << " Test :" <<this->test<< endl;
}
~ Test()
{
cout << " ~Test :" <<this->test<< endl;
}
private:
string test;
};
Test* GetText(string str)
{
return new Test(str);
}
class A
{
public:
A();
~ A();
private:
};
A:: A()
{
cout << "a"<<endl;
}
A::~ A()
{
cout << "~a" << endl;
}
void test1()
{
cout << "test1:" << endl;
Test* t = GetText("t");
delete t;
}
void test2()
{
cout << "test2:" << endl;
Test* t = GetText("t");
return;
delete t;
}
void text3()
{
cout << "test3:" << endl;
auto_ptr<Test> t2(GetText("t2"));
}
void text4()
{
cout << "test4:" << endl;
A a;
}
int main()
{
test1();
test2();
text3();
text4();
return 0;
}
运行结果如下:
但是auto_ptr有个缺点,就是他的=operator 会把之前存的引用给删除,意味着,它无法发挥正常的复制行为。
auto_ptr<Test> t1(GetText("t1"));
auto_ptr<Test> t2(t1);
cout << t1.get()<<endl;
cout << t2.get()<<endl;
t1 = t2;
cout << t1.get() << endl;
cout << t2.get() << endl;
解决方案就是 shared_ptr,它是引用计数形智能指针
他会持续追踪共用多少个对象指向某笔资源
cout <<endl<< "test2:" << endl;
shared_ptr<Test> t1(GetText("t1"));
shared_ptr<Test> t2(t1);
cout << t1.get() << endl;
cout << t2.get() << endl;
t1 = t2;
cout << t1.get() << endl;
cout << t2.get() << endl;
#include <iostream>
#include<string>
using namespace std;
class Test
{
public:
Test(string test) :test(test)
{
cout << " Test :" <<this->test<< endl;
}
~ Test()
{
cout << " ~Test :" <<this->test<< endl;
}
private:
string test;
};
Test* GetText(string str)
{
return new Test(str);
}
class A
{
public:
A();
~ A();
private:
};
A:: A()
{
cout << "a"<<endl;
}
A::~ A()
{
cout << "~a" << endl;
}
void test1()
{
cout << endl << "test1:" << endl;
auto_ptr<Test> t1(GetText("t1"));
auto_ptr<Test> t2(t1);
cout << t1.get()<<endl;
cout << t2.get()<<endl;
t1 = t2;
cout << t1.get() << endl;
cout << t2.get() << endl;
}
void test2()
{
cout <<endl<< "test2:" << endl;
shared_ptr<Test> t1(GetText("t1"));
shared_ptr<Test> t2(t1);
cout << t1.get() << endl;
cout << t2.get() << endl;
t1 = t2;
cout << t1.get() << endl;
cout << t2.get() << endl;
}
int main()
{
test1();
test2();
return 0;
}
运行结果: