当前位置:编程学习 > C/C++ >>

C++ - "shared_ptr" 拆分智能指针(smart pointer)

"shared_ptr" 拆分智能指针(smart pointer)
 
两个"shared_ptr"指针, 共享内存数据, 如果其中一个修改, 则对象(object)修改, 两个指针指向的数据均修改.
如果想把两个指针拆分开, 单独修改某一个, 则需要使用, unique()和reset()方法.
如下代码所示, 只修改p, 并保持q不变, 但是两个的使用数量(use_count)均由2变化为1.
代码:
 
/* 
 * CppPrimer.cpp 
 * 
 *  Created on: 2013.11.4 
 *      Author: C.L.Wang 
 */  
  
/*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++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,