Search code examples
c++pointersc++11shared-ptrsmart-pointers

How to change to avoid copying the contents of the pointers


EDIT 3

I have the following code

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 now points to the resource 6 and the output in the console is then 666. I like to avoid the copy *temp = *other as the real value I use in the pointers and stack are expensive to copy.


Solution

  • You just need to keep going with using pointer to pointer.

    //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;
    

    No, you cannot change in that way p2, it is alocated on stack, and keeping pointer to stack inside shared_ptr would be very incomprehensible.

    Anyway, I think that you might looking for flyweight pattern, see this.