C++中shared_ptr的使用

来源:互联网 发布:css书籍推荐 知乎 编辑:程序博客网 时间:2024/05/29 16:52

template class shared_ptr

#include<memory>

shared_ptr是C++ 11之后标准库引入的一个特性,用于简化内存管理,防止内存泄露。

1.shared_ptr的作用是什么?

Objects of shared_ptr types have the ability of taking ownership of a pointer and share that ownership: once they take ownership, the group of owners of a pointer become responsible for its deletion when the last one of them releases that ownership.注意,这个解释中有两个关键的词语take&&shared the ownership.

2.那么shared_ptr什么时候放弃对ownership的所有权呢?

shared_ptr objects release ownership on the object they co-own as soon as they themselves are destroyed, or as soon as their value changes either by an assignment operation or by an explicit call to shared_ptr::reset. Once allshared_ptr objects that share ownership over a pointer have released this ownership, the managed object is deleted (normally by calling ::delete, but a different deleter may be specified on construction).

3.引用计数的处理:两个shared_ptr指向同一个pointer时,情况如何?

shared_ptr objects can only share ownership by copying their value: If two shared_ptr are constructed (or made) from the same (non-shared_ptr) pointer, they will both be owning the pointer without sharing it, causing potential access problems when one of them releases it (deleting its managed object) and leaving the other pointing to an invalid location.

4.empty VS null pointer

shared_ptr that does not own any pointer is called an empty shared_ptr. A shared_ptr that points to no object is called a null shared_ptr and shall not be dereferenced. Notice though that an empty shared_ptr is not necessarily anull shared_ptr, and a null shared_ptr is not necessarily an empty shared_ptr.

5.常用函数

use_count
reset

6.使用实例

#include <iostream>#include <memory>using namespace std;class A{    public:        int a;        int b;        int c;        int d;};//16Bstd::shared_ptr<A> test(){    for (int i = 0; i < 1; ++i)    {        std::shared_ptr<A> pa(new A);        return pa;    }}int main(int argc, char *argv[]){    for (int i = 0; i < 1000*1000; ++i)    {        std::shared_ptr<A> pa = test();        cout << pa.use_count();    }    while(1);    return 0;}

上面是shared_ptr的使用实例,我们可以看到,其中并没有delete操作。我们将shared_ptr换成普通指针,然后利用top命令进行对比,就可以看到二者的所需要的内存大小的不同。

[1] weak_ptr
[2] shared_ptr包含在哪些库中?go to shared_ptr

0 0
原创粉丝点击