//
//一个简单的防止内存泄露的例子
//
void test() {
//使用RAII的特性管理资源
//当智能指针unique_ptr被销毁时,它指向的对象也将被销毁
//这里test函数返回后 p将自动销毁
//unique_ptr<int[]> p( new int[200] );
//直接生成资源
//test函数返回后 p不能被正常销毁,就会造成资源泄露
//int* p = new int[200];
}
int main()
{
while( 1 ) {
test();
Sleep( 1 );
}
return 0;
}
1 //[智能指针]操作测试
2
3 //######################################################################################################
4 //#【 unique_ptr 】
5 unique_ptr<string> unique_ptr__fn() {
6 //【 unique_ptr 】
7 // 是一个同一时间只能指向一个对象,并且不能被拷贝和赋值的智能指针
8 unique_ptr<string> a( new string( "test" ) ); //new出一个string 并使用'智能指针(a)'指向它
9 *a = "what? "; //修改指针a所指向的string的值
10 //unique_ptr<string> b( a ); //错误,不能被拷贝
11 //unique_ptr<string> c = a; //错误,不能被赋值
12 unique_ptr<string> d( a.release() ); //可以调用release()释放指针用以转交所有权, 注意:此时并不销毁指向的对象
13 cout << *d;
14 //d.reset(); //手动调用reset销毁指向的对象
15 //cout << *d; //错误,指向的对象已经被手动销毁
16
17 unique_ptr<string> e = move( d ); //unique_ptr 支持move() 说明unique_ptr中存在move构造
//so 也可以用来作为返回值
18 //cout << *d; //错误,指针d已经move到e
19
20 return e; //返回智能指针e
21 }
22
23 void test_unqiue_ptr() {
24 unique_ptr<string> f = unique_ptr__fn(); //此时f = move(e);
25 cout << *f;
26 }
27
28
29
30
31 //######################################################################################################
32 //#【 shared_ptr 】
33 void shared_ptr__fn( shared_ptr<string>& x) {
34 //【shared_ptr_test】
35 // 带有引用计数的智能指针,所以允许赋值与copy操作,仅当计数归0时才销毁指向的对象
36 // 所以这样看来 在不考虑效率的情况下 shared_ptr是可以代替unique_ptr的
37 // 但是对于一个不需要共享的资源来说,尽量使用unique_ptr
38 shared_ptr<string> a( x ); //copy构造 OK
39 cout << *a;
40 //shared_ptr<string> b = a; //copy构造 OK
41 //shared_ptr<string> c;
42 //c = b; //赋值操作 OK
43
44 return; //ret后局部指针a将失效,但是并不会销毁指向的对象
45 }
46
47 void shared_ptr_test() {
48 shared_ptr<string> x( new string( "test " ) ); //构造一个shared_ptr
49 shared_ptr__fn(x); //将指针x传入下个函数中
50
51 return; //ret后 对象将被销毁
52 }