如何更改以避免复制指针的内容
How to change to avoid copying the contents of the pointers
EDIT 3
我有以下代码std::shared_ptr<int> original = std::make_shared<int>(5);
std::shared_ptr<int> other = std::make_shared<int>(6);
std::stack<std::shared_ptr<int>> todo;
todo.push(original);
std::shared_ptr<int> temp = todo.top();
*temp = *other;
std::cout << original << other << temp << std::endl;
original
现在指向资源6
,控制台的输出则是666
。我喜欢避免复制*temp = *other
,因为我在指针和堆栈中使用的实际值复制起来很昂贵。
你只需要继续使用指针对指针。
//we need to make shared pointer to shared pointer
const std::shared_ptr<std::shared_ptr<int>> orginal =
std::make_shared<std::shared_ptr<int>>(std::make_shared<int>(5));
// const pp1 must be declarated before p1 to make sure p1 is valid
std::shared_ptr<int> &p1 = *orginal;
std::shared_ptr<int> p2 = std::make_shared<int>(6);
cout << *p1 << *p2 << endl;
std::stack<std::shared_ptr<std::shared_ptr<int>>> todo;
//we cannot add p1, instead we need to add orginal
todo.push(orginal);
std::shared_ptr<std::shared_ptr<int>> temp = todo.top();
//this does change the orginal
*temp = p2;
cout << *p1 << *p2 << endl;
不,你不能这样改变p2
,它是在堆栈上分配的,在shared_ptr中保持指向堆栈的指针是非常不可理解的。
无论如何,我认为你可能在寻找flyweight模式,看这个
我认为如果你使用weak_ptr
作为堆栈的模板参数,你可以实现你正在寻找的:
std::shared_ptr<int> original = std::make_shared<int>(5);
std::shared_ptr<int> other = std::make_shared<int>(6);
std::stack<std::weak_ptr<int>> todo;
todo.push(original);
std::weak_ptr<int> temp = todo.top();
temp=other;
std::cout << *original.get() << *other.get() << *temp.lock().get() << std::endl;
std::cout<<"use_count: original:"<< original.use_count()<<"n";
std::cout<<"use_count: other:"<< other.use_count()<<"n";
输出:566
use_count:原:1
use_count:其他:1
编辑:std::shared_ptr<int> original = std::make_shared<int>(5);
std::shared_ptr<int> other = std::make_shared<int>(6);
std::stack<std::weak_ptr<int>> todo;
todo.push(original);
std::weak_ptr<int> temp = todo.top();
temp=other;
original= other;
std::cout << *original.get() << *other.get() << *temp.lock().get() << std::endl;
std::cout<<"use_count: original:"<< original.use_count()<<"n";
std::cout<<"use_count: other:"<< other.use_count()<<"n";
std::cout<<"use_count: temp:"<< temp.use_count()<<"n";
输出:666
use_count:原:2
use_count:其他:2
use_count:温度:2
相关文章:
- C++指针复制重载
- 将值从指针复制到常量对象参数
- 在 C++ 中通过字符串指针复制字符串变量中的字符串
- 使用指针复制构造函数用法
- 将对象的指针复制到此对象的新指针中
- 如何将指向 int(数组)的指针复制到 int 数组?
- 从指针复制对象
- C 使用指针复制char*
- 使用随机指针C 复制列表
- 如何在C++中从void指针复制数据
- 在 C++ 中将一个指针复制到另一个指针
- 正在将指针复制到assign运算符中的另一个列表元素
- 从压缩的DIB无效指针复制
- 无法从字符指针复制到短
- C++使用指针复制构造函数
- 将对象指针复制到动态对象数组中
- 在 CUDA 中使用指针复制类
- 从指针复制派生对象
- 如何使用智能指针复制C++更改指针
- 将内容从一个指针复制到另一个指针