Boost logo

Boost Users :

Subject: [Boost-users] How & when to use weak_ptr
From: doug livesey (biot023_at_[hidden])
Date: 2011-07-02 12:28:48

Hi -- I'm loving how easy shared_ptr makes object handling, but am not sure
about how to use weak_ptr.
Should I use it in places where previously I would have, say, returned a
const reference?
For example:
  struct MyClass {
    const OtherObject & other_object() const;

Would become:
  struct MyClass {
    weak_ptr<const OtherObject> other_object() const;

Or is this wasteful, having weak_ptrs construct from shared_ptrs every time
I want to access an member object?
Or have I missed the point completely? ;)

One convention I thought I might adopt would be like this:
  struct MyClass {
    void set_other_object( shared_ptr<OtherObject> ); // setter
    weak_ptr<OtherObject> get_other_object(); // non-const getter
    const OtherObject & other_object() const; // const getter

Of course, that could be all kinds of dumb for all kinds of reasons I don't
know about. :)

Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at