热爱互联网

c++ 11 —- shared_ptr

详见:http://en.cppreference.com/w/cpp/memory/shared_ptr

shared_ptr 是通过指针保持某个对象的共享拥有权的智能指针。若干个 shared_ptr 对象可以拥有同一个对象;最后一个指向该对象的 shared_ptr 被销毁或重置时,该对象被销毁。销毁该对象时使用的是 delete 表达式或者是在构造 shared_ptr 时传入的自定义删除器(deleter)。

下面是个小例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<iostream>
#include<string>
#include<memory>
using namespace std;
 
struct Foo{
	Foo(){
		cout << "Foo..." <<endl;
	}
	~Foo(){
		cout << "~Foo..." <<endl;
	}
};
 
struct D{
	void operator()(Foo* p) const{
		cout << "call delete for Foo object..." <<endl;
		delete p;
	}
};
 
int main()
{
	shared_ptr<foo> sh1;
 
	shared_ptr<foo> sh2(new Foo);
	shared_ptr<foo> sh3(sh2);
 
	cout << sh2.use_count() << endl;
	cout << sh3.use_count() << endl;
 
	shared_ptr<foo> sh4(new Foo,D());
 
	shared_ptr<foo> sh5 = sh4;
 
	cout << "hello world" <<endl;
 
	return 0;
}

Post a Comment

Your email is kept private. Required fields are marked *