sunny
sunny

Reputation: 189

Calling a function on weak pointer

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.

Upvotes: 1

Views: 1184

Answers (1)

Tom Kerr
Tom Kerr

Reputation: 10720

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!
}

Upvotes: 3

Related Questions