0

I have written the following code:

#include <iostream>
#include <memory>
using namespace std;

class Foo
{
    int x = 0;
public:
    int get() const { return x; }
    void set(int x) { this->x = x; }
};

int main(){
    auto sp = shared_ptr<Foo>(new Foo());    
    weak_ptr<Foo> wp;
    wp = sp;
    return 0;
}

I want to call the method set on the shared pointer sp and also on wp, what will be the proper way to call it? I found that sp->set(5); works for a shared pointer, but the same doesn't work for the weak pointer.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
sunny
  • 149
  • 8
  • 2
    https://en.cppreference.com/w/cpp/memory/weak_ptr is a good overview. You have to convert it back to a shared pointer with `.lock()`. – Nate Eldredge Aug 20 '21 at 23:36
  • `weak_ptr wp; wp=sp; auto spt = wp.lock(); spt->set(10);` Is this a correct way? – sunny Aug 20 '21 at 23:56
  • 1
    Yes, but keep in mind that `spt` could be empty if the original `Foo` object has run out of non-weak references and been deleted, in which case `spt->set(10)` causes undefined behavior. You should test for this case. Or use the constructor: `shared_ptr spt = wp;` which will throw an exception in that situation. – Nate Eldredge Aug 21 '21 at 00:00
  • well, this question des not show any effort on research, since one can easily find out the answer to this by reading the documentation on cppreference for `std::weak_ptr` – Sergey Kolesnik Aug 21 '21 at 19:01

1 Answers1

1

You cannot operate on a weak_ptr. If the shared_ptr has been deleted, it would be like dereferencing a raw pointer that had been deleted.

Whenever you want to access the pointer contained in it, you would lock it to verify your shared_ptr still exists.

if (auto sp = wp.lock()) {
  sp->set(10);
} else {
  // sp no longer exists!
}
Tom Kerr
  • 10,444
  • 2
  • 30
  • 46