unique_ptr
auto_ptr强调的是所有权,拷贝和赋值都会让原对象失去控制权,再使用原对象可能会造成崩溃,和STL容器、算法也不能很好的配合。
在c++11里auto_ptr的功能被unique_ptr替代,与auto_ptr相比,uniqie_ptr主要有以下不同:
- 安全的控制权转移
unique_ptr构造函数和赋值函数不再接受同类对象的左值引用,只接受右值引用。这使得以下的语句1)编译时直接报错。
unique_ptr<int> make_int(int i)
{
return unique_ptr<int>(new int(i));
}
unique_ptr<int> a(new int(6));
unique_ptr<int> b = a; //1) 编译时报错
unique_ptr<int> c = make_int(8);
- 支持指针数组
unique_ptr提供指针数组特化版本,如unique_ptr<int[]> c(new int[3]);
,在释放资源时使用delete []。
同时该版本还提供了T& operator[](size_t i) const;
。
- 支持用户使用自定义Deleter。
unique_ptr的声明是:template <class T, class Deleter = std::default_delete<T>> class unique_ptr;
,非特化的default_delete用delete解分配单个对象的内存,亦提供针对数组类型的特化。
下面的例子中,当打开文件失败时指针为空,fclose最终不会被调用:
unique_ptr<FILE, int(*)(FILE*)> c(fopen("test.txt", "r"), &fclose);
unique_ptr<FILE, decltype(&fclose)> d(fopen("test.txt", "r"), fclose);
unique_ptr<FILE, std::function<int(FILE*)>> fp(fopen("test.txt", "r"), [](FILE *file){fclose(file);});
shared_ptr
unique_ptr也不能和容器、算法配合,shared_ptr是一个更全面的选手,也更正常,使用引用计数使多个对象共享一块存储。
long use_count() const noexcept;
用来获得管理当前对象的不同shared_ptr实例数量。
- Deleter
shared_ptr的目模板参数是不包含Deleter的:template <class T> class shared_ptr;
,但它的构造函数可以接受Deleter:
template <class U, class D> shared_ptr(U* p, D del);
template <class D> shared_ptr(nullptr_t p, D del);
shared_ptr会将del放到所管理的对象中。
- 一些相关的全局函数
template <class T, class... Args>
shared_ptr<T> make_shared(Args&&... args);
Allocates and constructs an object of type T passing args to its constructor,
and returns an object of type shared_ptr<T> that
owns and stores a pointer to it (with a use count of 1).
This function uses ::new to allocate storage for the object.
template <class T, class Alloc, class... Args>
shared_ptr<T> allocate_shared(const Alloc& alloc, Args&&... args);
与make_shared类似,但使用alloc来分配存储。
template <class T, class U>
shared_ptr<T> static_pointer_cast(const shared_ptr<U>& sp) noexcept;
template <class T, class U>
shared_ptr<T> dynamic_pointer_cast(const shared_ptr<U>& sp) noexcept;
template <class T, class U>
shared_ptr<T> const_pointer_cast(const shared_ptr<U>& sp) noexcept;
返回sp的一个拷贝,分别通过static_cast、dynamic_cast、const_cast对其存储的指针进行转换。
如果sp非空,返回的对象共享sp资源,use_count()加1。
- 区分stored pointer和owned pointer
owned pointer:负责内存管理的指针
stored pointer:shared_ptr::get返回的指针
通常来说这俩是一个东西,但有一个特殊的构造函数:
template <class U> shared_ptr(const shared_ptr<U>& x, element_type* p) noexcept;
返回对象的stored pointer是p,但它不拥有p,不管理p的存储。它管理的是x所管理的对象,x的use_count()加1。
shared_ptr之间的比较操作比较的是stored pointer,如要基于owned pointer的比较,使用owner_less:
template <class Ptr> struct owner_less;
template <class T> struct owner_less<shared_ptr<T>>;
template <class T> struct owner_less<weak_ptr<T>>;
owner_less的operator()函数对shared_ptr和shared_ptr、shared_ptr和weak_ptr进行比较,实际调用了shared_ptr和weak_ptr的owner_before函数。例如:
#include <iostream>
#include <memory>
int main () {
int * p = new int (20);
std::shared_ptr<int> a (new int (20));
std::shared_ptr<int> b (a,p);
std::shared_ptr<int> c (b,p);
std::cout << std::boolalpha;
std::cout << "value-based a==b: " << ( !(a<b) && !(b<a) ) << '\n';
std::cout << "value-based b==c: " << ( b == c ) << '\n';
std::cout << "owner-based a==b: " << ( !a.owner_before(b) && !b.owner_before(a) ) << '\n';
std::owner_less<std::shared_ptr<int>> less_int_ptr;
std::cout << "owner-based b==c: " << ( !less_int_ptr(b,c) && !less_int_ptr(c,b) ) << '\n';
delete p;
return 0;
}
value-based a==b: false
value-based b==c: true
owner-based a==b: true
owner-based b==c: true
weak_ptr
shared_ptr is very good. 但循环引用的情况下会存在内存泄漏问题:
struct Node {
shared_ptr<Node> next;
~Node() { cout << "destroy\n"; }
};
void func() {
shared_ptr<Node> p1(new Node);
shared_ptr<Node> p2(new Node);
cout << p1.use_count();
cout << p2.use_count();
p1->next = p2;
p2->next = p1;
cout << p1.use_count();
cout << p2.use_count() << endl;
}
这时候我们需要weak_ptr,weak_ptr包含一个到shared_ptr管理对象的non-owning(weak)引用,要访问其引用的对象必须先转换为shared_ptr。weak_ptr不影响shared_ptr的引用计数,如果引用计数达到0,即使weak_ptr还指向这个对象,这个对象也会被销毁。
long int use_count() const noexcept;
返回0当管理的对象已经被删除时
bool expired() const noexcept;
等价于use_count() == 0
void reset() noexcept;
释放对管理对象的引用
std::shared_ptr<T> lock() const noexcept;
Creates a new std::shared_ptr that shares ownership of the managed object.
If there is no managed object, i.e. *this is empty, then the returned shared_ptr also is empty.
Effectively returns expired() ? shared_ptr<T>() : shared_ptr<T>(*this), executed atomically.