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

How to change to avoid copying the contents of the pointers

本文关键字:指针 复制 何更改      更新时间:2023-10-16

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