C++ - "shared_ptr" 拆分智能指针(smart pointer)
2013-11-04 16:34
381 查看
"shared_ptr" 拆分智能指针(smart pointer)
两个"shared_ptr"指针, 共享内存数据, 如果其中一个修改, 则对象(object)修改, 两个指针指向的数据均修改.如果想把两个指针拆分开,单独修改某一个, 则需要使用, unique()和reset()方法.
如下代码所示, 只修改p, 并保持q不变, 但是两个的使用数量(use_count)均由2变化为1.
代码:
/* * CppPrimer.cpp * * Created on: 2013.11.4 * Author: Caroline */ /*eclipse cdt GCC 4.8.1*/ #include <iostream> #include <vector> #include <string> #include <memory> #include <new> using namespace std; int main (void) { std::shared_ptr<int> p(new int(256)); std::shared_ptr<int> q = p; std::cout << "original : " << std::endl; std::cout << "*p = " << *p << std::endl; std::cout << "*q = " << *q << std::endl; std::cout << "p use count : " << p.use_count() << std::endl; *p += 256; std::cout << "plus : " << std::endl; std::cout << "*p = " << *p << std::endl; std::cout << "*q = " << *q << std::endl; std::cout << "p use count : " << p.use_count() << std::endl; if(!p.unique()) p.reset(new int(*p)); *p += 512; std::cout << "reset : " << std::endl; std::cout << "*p = " << *p << std::endl; std::cout << "*q = " << *q << std::endl; std::cout << "p use count : " << p.use_count() << std::endl; return 0; }
输出:
original :
*p = 256
*q = 256
p use count : 2
plus :
*p = 512
*q = 512
p use count : 2
reset :
*p = 1024
*q = 512
p use count : 1
相关文章推荐
- C++ - "shared_ptr" 拆分智能指针(smart pointer)
- c++ smart pointer之shared_ptr
- 智能指针(模拟实现auto_ptr,shared_ptr,scooeptr 以及定制删除器c++ 实现)
- C++ - "shared_ptr"的使用方法 及 代码
- C++ - "shared_ptr"的使用方法 及 代码
- C++实现智能指针(shared_ptr和unique_ptr)与删除器
- 智能指针shared_ptr
- 失足于shared_ptr - 力为的技术博客 - C++博客
- C++简单版shared_ptr智能指针的实现
- [C++] Boost智能指针——boost::shared_ptr(使用及原理分析)
- C++11智能指针Shared_ptr
- C++ shared_ptr源码剖析
- c++ the difference between auto_ptr (or unique_ptr) and shared_ptr
- [置顶] 从零开始学C++之boost库(一):详解 boost 库智能指针(scoped_ptr<T> 、shared_ptr<T> 、weak_ptr<T> 源码分析)
- 智能指针:auto_ptr和shared_ptr
- c++【深度剖析shared_ptr】
- c++ shared_ptr的错误用法之cycle引用
- C++ 之 constexpr And shared_ptr
- 智能指针(二):shared_ptr实现原理
- Effective Modern C++ 条款19 用std::shared_ptr管理共享所有权的资源