0

I am a complete newbie to smart pointers, and I have never dealt with weak_ptr in C++.

I have a function in class Y, that takes in as parameter a weak_ptr of class X.

Inside the function in class Y, I need to access the member functions of class X through the weak_ptr.

For reference, here is a rough class definition:

Y.cpp

class Y {
  public : Y();
           ~Y();
           int foo(std::weak_ptr<X> x);
};

X.cpp

class X {
 public : std::string func1();
          int func2();
};

Inside of the foo() function in class Y, I need to be able to access the functions func1 and func2 using the weak_ptr x.

I don't know why I need to use weak_ptr, but that's what I am supposed to implement.

I am unable to find any beginner-friendly sample code using weak_ptr.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Harini Sj
  • 173
  • 1
  • 2
  • 11

1 Answers1

6

You need to convert it to a shared_ptr first, using .lock():

int foo(std::weak_ptr<X> x)
{
    std::shared_ptr<X> y = x.lock(); // Or `auto y = x.lock();`.
    y->do_stuff();
}

The rationale is that a weak_ptr doesn't hold ownership (unlike shared_ptr), so if you could dereference it directly, there would be a risk of the target object being destroyed from a different thread while you're doing that.

It's might be a good idea to check if the resulting pointer (y) is not null before using it, unless crashing if it's null is an acceptable way to handle an error in your case.

It's a bad idea to call .lock() every time (instead of once and saving the result to a variable), since the target can be destroyed between calls (and it would be more costly).

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207