如何更改以避免复制指针的内容

How to change to avoid copying the contents of the pointers

编辑 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 因为我在指针和堆栈中使用的实际值复制起来很昂贵。

我想如果你使用 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: original:1

use_count: other: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: original:2

use_count: other:2

use_count: temp:2

您只需要继续使用指向指针的指针即可。

//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中是非常不可理解的。

无论如何,我认为您可能正在寻找享元模式,see this