1.auto_ptr:
该指针在c++98中采用,cpp11已经弃用。
2.unique_ptr:
该指针实现独占式或者严格拥有概念,保证同一时间内只有一个智能指针指向该对象。
使用方法:
1.unique_ptr e1(new entity());
2.unique_ptr e1 = make_unique();
3.auto e1 = make_unique();
4.unique_ptr e2 = move(e1);//此时e1是一个空指针,movable,transfer ownership
注意:unique_ptr e2 = e1 错误的赋值方式,因为该智能指针是一个single ownership
5.foo(move(e1));//函数调用
例1:
class entity //类entity
{
public:
entity(){cout << "entity created!";}
~entity(){cout << "entity destroyed!";}
}
void ex1(){
cout << " ";
cout << "entering ex1";
{
cout << "entering ex1::scope1";
auto e1 = make_unique<entity>();
cout << "leaving ex1::scope1";
}
cout << "leacing ex1";
}
结果:
entering ex1
entering ex1::scope1
entity created!
leaving ex1::scope1
entity destroyed!
leacing ex1
例2:
void foo(unique_ptr<entity>){
cout << "emtering foo";
cout << "leaving foo";
}
void ex2(){
cout << "entering ex2";
auto e1 = make_unique<entity>();
foo(move(e1));
cout << "leaving ex2";
}
结果:
entering ex2
entity created!
entering foo
leaving foo
entity destroyed!
leaving ex2
3.shared_ptr:
该指针实现共享式拥有概念,多个智能指针可以指向同一个对象,该对象及其相关资源在“最后一个引用被摧毁”时释放。shared_ptr 是为了解决 auto_ptr 在对象所有权上的局限性(auto_ptr 是独占的), 在使用引用计数的机制上提供了可以共享所有权的智能指针。
shared_ptr指针的使用跟unique_ptr类似。
成员函数:
use_count: 返回引用计数的个数;
get 返回内部对象(指针), 由于已经重载了()方法, 因此和直接使用对象是一样的.如 shared_ptr sp(new int(1)); sp 与 sp.get()是等价的。
例子:
void ex3(){
cout << "entering ex3";
auto e1 = make_shared<entity>();
cout << e1.use_count();
{
cout << "entering ex3::scope3";
auto e2 = e1;//use_count++
cout << e1.use_count();
auto e3 = move(e2);//use_count remains
cout << e1.use_count();
cout << "leaving ex3::scope3";
}
cout << e1.use_count();
count << "leacing ex3";
}
结果:
entering ex3
entity created!
1
entring ex3::scope3
2
2
leaving ex3::scope3
1
leaving ex3
entity destroyed!
4.weak_ptr:
weak_ptr 是一种不控制对象生命周期的智能指针, 它指向一个 shared_ptr 管理的对象. 进行该对象的内存管理的是那个强引用的 shared_ptr. weak_ptr只是提供了对管理对象的一个访问手段。与shared_ptr配合使用,不过与shared_ptr不同的是:weak_ptr不会引起引用计数的增加或者减少。