C++智能指针 shared_ptr
  shared_ptr 是一个标准的共享所有权的智能指针, 允许多个指针指向同一个对象. 定义在 memory 文件中(非memory.h), 命名空间为 std.

std::shared_ptr<int> sp1 = std::make_shared<int>(10);
std::shared_ptr<std::string> sp2 = std::make_shared<std::string>("Hello c++");
auto sp4 = std::make_shared<std::string>("c++11");
printf("sp4=%s\n", (*sp4).c_str());

1.use_count 返回引用计数的个数
2.unique 返回是否是独占所有权( use_count 为 1)
3.swap 交换两个 shared_ptr 对象(即交换所拥有的对象)
4.reset 放弃内部对象的所有权或拥有对象的变更, 会引起原有对象的引用计数的减少
5.get 返回内部对象(指针), 由于已经重载了()方法, 因此和直接使用对象是一样的.如 shared_ptr<int> sp(new int(1)); sp 与 sp.get()是等价的

std::shared_ptr<int> sp0(new int(2));
std::shared_ptr<int> sp1(new int(11));
std::shared_ptr<int> sp2 = sp1;
printf("%d\n", *sp0);               // 2
printf("%d\n", *sp1);               // 11
printf("%d\n", *sp2);               // 11
sp1.swap(sp0);
printf("%d\n", *sp0);               // 11
printf("%d\n", *sp1);               // 2
printf("%d\n", *sp2);               // 11

std::shared_ptr<int> sp3(new int(22));
std::shared_ptr<int> sp4 = sp3;
printf("%d\n", *sp3);               // 22
printf("%d\n", *sp4);               // 22
sp3.reset();                       
printf("%d\n", sp3.use_count());    // 0
printf("%d\n", sp4.use_count());    // 1
printf("%d\n", sp3);                // 0
printf("%d\n", sp4);                // 指向所拥有对象的地址
           
std::shared_ptr<int> sp5(new int(22));
std::shared_ptr<int> sp6 = sp5;
std::shared_ptr<int> sp7 = sp5;
printf("%d\n", *sp5);               // 22
printf("%d\n", *sp6);               // 22
printf("%d\n", *sp7);               // 22
printf("%d\n", sp5.use_count());    // 3
printf("%d\n", sp6.use_count());    // 3
printf("%d\n", sp7.use_count());    // 3
sp5.reset(new int(33));                       
printf("%d\n", sp5.use_count());    // 1
printf("%d\n", sp6.use_count());    // 2
printf("%d\n", sp7.use_count());    // 2
printf("%d\n", *sp5);               // 33
printf("%d\n", *sp6);               // 22
printf("%d\n", *sp7);               // 22

shared_ptr 的赋值构造函数和拷贝构造函数:
auto r = std::make_shared<int>(); // r的指向的对象只有一个引用, 其 use_count == 1
auto q = r; // r指向的对象的引用计数加1, 此时 q 与 r 指向同一个对象, 并且其引用计数相同, 都为原来的值加1.

使用 shared_ptr 的注意事项
(1) shared_ptr 作为被保护的对象的成员时, 小心因循环引用造成无法释放资源.
假设 a 对象中含有一个 shared_ptr<CB> 指向 b 对象, b 对象中含有一个 shared_ptr<CA> 指向 a 对象, 并且 a, b 对象都是堆中分配的
考虑对象 b 中的 m_spa 是我们能最后一个看到 a 对象的共享智能指针, 其 use_count 为2, 因为对象 b 中持有 a 的指针, 所以当 m_spa 说再见时,
m_spa 只是把 a 对象的 use_count 改成1; 对象 a 同理; 然后就失去了 a,b 对象的联系.
解决此方法是使用 weak_ptr 替换 shared_ptr . 以下为错误用法, 导致相互引用, 最后无法释放对象

运行下述代码会发现 CA, CB 析构函数都不会打印. 因为他们都没有释放内存.
class CB;
            class CA;

class CA
            {
            public:
                CA(){}
                ~CA(){PRINT_FUN();}

void Register(const std::shared_ptr<CB>& sp)
                {
                    m_sp = sp;
                }

private:
                std::shared_ptr<CB> m_sp;
            };

class CB
            {
            public:
                CB(){};
                ~CB(){PRINT_FUN();};

void Register(const std::shared_ptr<CA>& sp)
                {
                    m_sp = sp;
                }

private:
                std::shared_ptr<CA> m_sp;
            };

std::shared_ptr<CA> spa(new CA);
            std::shared_ptr<CB> spb(new CB);

spb->Register(spa);
            spa->Register(spb);
            printf("%d\n", spb.use_count()); // 2
            printf("%d\n", spa.use_count()); // 2

(2) 小心对象内部生成 shared_ptr
class Y : public std::enable_shared_from_this<Y>
{
public:
       std::shared_ptr<Y> GetSharePtr()
       {
            return shared_from_this();
        }
};

对普通的类(没有继承 enable_shared_from_this) T 的 shared_ptr<T> p(new T). p 作为栈对象占8个字节,为了记录( new T )对象的引用计数, p 会在堆上分配 16 个字节以保存引用计数等“智能信息”.
    share_ptr 没有“嵌入(intrusive)”到T对象, 或者说T对象对 share_ptr 毫不知情.
    而 Y 对象则不同, Y 对象已经被“嵌入”了一些 share_ptr 相关的信息, 目的是为了找到“全局性”的那16字节的本对象的“智能信息”.
考虑下面的代码:
            Y y;
            std::shared_ptr<Y> spy = y.GetSharePtr(); // 错误, y 根本不是 new 创建的
            Y* y = new Y;
            std::shared_ptr<Y> spy = y->GetSharePtr(); // 错误, 问题依旧存在, 程序直接崩溃
        正确用法:
            std::shared_ptr<Y> spy(new Y);
            std::shared_ptr<Y> p = spy->GetSharePtr();
            printf("%d\n", p.use_count()); // 2

(3) 小心多线程对引用计数的影响
首先, 如果是轻量级的锁, 比如 InterLockIncrement 等, 对程序影响不大; 如果是重量级的锁, 就要考虑因为 share_ptr 维护引用计数而造成的上下文切换开销.
其次, 多线程同时对 shared_ptr 读写时, 行为不确定, 因为shared_ptr本身有两个成员px,pi. 多线程同时对 px 读写要出问题, 与一个 int 的全局变量多线程读写会出问题的原因一样.
(4) 与 weak_ptr 一起工作时, weak_ptr 在使用前需要检查合法性
std::weak_ptr<A> wp;
        {
            std::shared_ptr<A>  sp(new A);  //sp.use_count()==1
            wp = sp; //wp不会改变引用计数,所以sp.use_count()==1
            std::shared_ptr<A> sp2 = wp.lock(); //wp没有重载->操作符。只能这样取所指向的对象
        }
        printf("expired:%d\n", wp.expired()); // 1
        std::shared_ptr<A> sp_null = wp.lock(); //sp_null .use_count()==0;

(5) shared_ptr 不支持数组, 如果使用数组, 需要自定义删除器, 如下是一个利用 lambda 实现的删除器:
      std::shared_ptr<int> sps(new int[10], [](int *p){delete[] p;});

对于数组元素的访问, 需使要使用 get 方法取得内部元素的地址后, 再加上偏移量取得. 
for (size_t i = 0; i < 10; i++)
            {
                *((int*)sps.get() + i) = 10 - i;
            }

for (size_t i = 0; i < 10; i++)
            {
                printf("%d -- %d\n", i, *((int*)sps.get() + i));
            }

share_ptr_c++11的更多相关文章

  1. 地区sql

    /*Navicat MySQL Data Transfer Source Server : localhostSource Server Version : 50136Source Host : lo ...

  2. WinForm 天猫2013双11自动抢红包【源码下载】

    1. 正确获取红包流程 2. 软件介绍 2.1 效果图: 2.2 功能介绍 2.2.1 账号登录 页面开始时,会载入这个网站:https://login.taobao.com/member/login ...

  3. C++11特性——变量部分(using类型别名、constexpr常量表达式、auto类型推断、nullptr空指针等)

    #include <iostream> using namespace std; int main() { using cullptr = const unsigned long long ...

  4. CSS垂直居中的11种实现方式

    今天是邓呆呆球衣退役的日子,在这个颇具纪念意义的日子里我写下自己的第一篇博客,还望前辈们多多提携,多多指教! 接下来,就进入正文,来说说关于垂直居中的事.(以下这11种垂直居中的实现方式均为笔者在日常 ...

  5. C++ 11 多线程--线程管理

    说到多线程编程,那么就不得不提并行和并发,多线程是实现并发(并行)的一种手段.并行是指两个或多个独立的操作同时进行.注意这里是同时进行,区别于并发,在一个时间段内执行多个操作.在单核时代,多个线程是并 ...

  6. CSharpGL(11)用C#直接编写GLSL程序

    CSharpGL(11)用C#直接编写GLSL程序 +BIT祝威+悄悄在此留下版了个权的信息说: 2016-08-13 由于CSharpGL一直在更新,现在这个教程已经不适用最新的代码了.CSharp ...

  7. ABP(现代ASP.NET样板开发框架)系列之11、ABP领域层——仓储(Repositories)

    点这里进入ABP系列文章总目录 基于DDD的现代ASP.NET开发框架--ABP系列之11.ABP领域层——仓储(Repositories) ABP是“ASP.NET Boilerplate Proj ...

  8. C++11 shared_ptr 智能指针 的使用,避免内存泄露

    多线程程序经常会遇到在某个线程A创建了一个对象,这个对象需要在线程B使用, 在没有shared_ptr时,因为线程A,B结束时间不确定,即在A或B线程先释放这个对象都有可能造成另一个线程崩溃, 所以为 ...

  9. C++11网络编程

    Handy是一个简洁优雅的C++11网络库,适用于linux与Mac平台.十行代码即可完成一个完整的网络服务器. 下面是echo服务器的代码: #include <handy/handy.h&g ...

随机推荐

  1. 452. Minimum Number of Arrows to Burst Balloons

    There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided ...

  2. 使用 cacti 监控 windows 服务器硬盘的 I/O 状况

    https://blog.csdn.net/m0_37814112/article/details/80742433

  3. java web获取请求体内容

    Java Web中如何获取请求体内容呢? 我们知道请求方式分为两种:Get,Post. /*** * Compatible with GET and POST * * @param request * ...

  4. C# 之 Structure 和 Class的区别

    一.类与结构的示例比较: 结构示例: public struct Person { string Name; int height; int weight public bool overWeight ...

  5. 无法删除另一个分区的windows文件夹

    转自:http://zhidao.baidu.com/link?url=77mJiLzVTdr9LzW4R6UYHZ8OJovvXsH8HQb0hyUKL4RKv2J3bItFJgJx-xqAEGOj ...

  6. Python连接mysql出错,_mysql_exceptions.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)")

  7. Python学习(六) —— 函数

    一.函数的定义和调用 为什么要用函数:例如,计算一个数据的长度,可以用一段代码实现,每次需要计算数据的长度都可以用这段代码,如果是一段代码,可读性差,重复代码多: 但是如果把这段代码封装成一个函数,用 ...

  8. 如何让你的数据有null

    2018-11-13   09:25:17 如何让你的数据有null 返回时null属性不显示: String str = JSONObject.toJSONString(obj); 返回为null属 ...

  9. Python 枚举 enum

    Python 枚举 enum enum 标准模块在 3.4 版本才可以使用,3.3 以下版本需要独立安装:https://pypi.python.org/pypi/enum34#downloads,官 ...

  10. Codeforces 208A-Dubstep(字符串)

    Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performanc ...