【发布时间】:2015-07-30 12:54:51
【问题描述】:
编辑 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,因为我在指针和堆栈中使用的实际值复制起来很昂贵。
【问题讨论】:
-
您更愿意将 p1 的旧值与 P2s 值结转吗?这就是你要找的吗?
-
也许我不明白...But what is wrong with
p1 = p2;? -
p2.swap(p1);不会成功吗? -
@satanik 每个人都很难理解你在问什么。假设您有两个
shared_ptrs,都拥有相同的资源 -auto p1 = std::make_shared<int>(10); auto p2 = p1;现在您想要发生什么?是否要将10替换为另一个值,以便*p1和*p2都产生新值?还是你在问别的?除非有必要,否则我建议删除shared_ptr<shared_ptr<int>>示例,并以简单的方式解释您的问题。 -
你更容易理解的例子不是。
标签: c++ pointers c++11 shared-ptr smart-pointers