[shared_ptr] Problem refeering back to a parent class.

Hello, I've a question, I don't know if I'm doing something technically wrong or if my whole approach is totally wrong. To explain I have a class (foo) managed by a shared_ptr and it contains a member class (bar) with needs to access some members of foo. So I figure I need some sort of pointer in the bar class back to the foo class. I thought using a weak_ptr was the obvious choice, here is what I came up with it; using namespace boost; class foo; class bar { public: bar(weak_ptr<foo> f) : foo_(f) {} private: weak_ptr<foo> foo_; }; class foo : public boost::enable_shared_from_this<foo> { public: foo() : bar_(shared_from_this()) {} private: bar bar_; }; But I get a boost::bad_weak_ptr error. Now if I use regular pointers instead of weak_ptr's I can get stuff working except that when I use "bar_(this)" in the initialization list for foo MSVC 7.1 gives me a warning, which I don't like. Is there a more appropriate method I should be using to accomplish this. Kind Regards, Eoin.

Eoin wrote:
But I get a boost::bad_weak_ptr error. Now if I use regular pointers instead of weak_ptr's I can get stuff working except that when I use "bar_(this)" in the initialization list for foo MSVC 7.1 gives me a warning, which I don't like. Is there a more appropriate method I should be using to accomplish this.
Just use a regular pointer. As the bar object is a subobject of foo, it is guaranteed to be destructed first, meaning that the pointer can never be invalid in the lifetime of bar. Sebastian Redl

Sebastian Redl wrote:
Eoin wrote:
But I get a boost::bad_weak_ptr error. Now if I use regular pointers instead of weak_ptr's I can get stuff working except that when I use "bar_(this)" in the initialization list for foo MSVC 7.1 gives me a warning, which I don't like. Is there a more appropriate method I should be using to accomplish this.
Just use a regular pointer. As the bar object is a subobject of foo, it is guaranteed to be destructed first, meaning that the pointer can never be invalid in the lifetime of bar.
Sebastian Redl
May I second that. There's an example somewhere on the web of using another shared_ptr but with a null destructor, which I followed. The following day, I realised it was a complete waste of time - you only need one shared ptr after all to get rid of all the horrible double free errors! :) Rupert
participants (3)
-
Eoin
-
Rupert Swarbrick
-
Sebastian Redl