Boost logo

Boost Users :

Subject: Re: [Boost-users] Problem with enable_shared_from_this and shared_ptr
From: Ryan McConnehey (mccorywork_at_[hidden])
Date: 2010-08-06 03:40:56

Ganeshram Iyer wrote:
Is there any chance you can post what you added to your provided example to fix the problem you were having? I would love to see what that example looks like when it is working.
Thanks in advance
Sorry for the delay in answering your question.  I missed it in my inbox.  Anyway I've included what I changed in the code.  I didn't see any point in giving the user a choice in how pool was created when one of the option gives an error.  So, I added a static methods that creates a pool in a shared_ptr and hid the constructor.  This forced the user to get the pool inside a shared_ptr and removed the possibility of an error when calling the get method.



//C++ Includes
#include <exception>
#include <iostream>
#include <vector>
#include <algorithm>

//Boost Includes
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>

class pool : public boost::enable_shared_from_this< pool >  {
 using boost::enable_shared_from_this< pool >::shared_from_this;


 static boost::shared_ptr<pool> create(void) {
   return boost::shared_ptr<pool>(new pool);

 boost::shared_ptr<int> get(void)  {
   boost::shared_ptr<pool> aPool = shared_from_this();   //This is where the tr1::bad_weak_ptr happens.
   return boost::shared_ptr<int>(new int);

int main(int argc, char * argv[]) {
 try {
   boost::shared_ptr<pool> myPool = pool::create();

   boost::shared_ptr<int> a = myPool->get();
 catch (std::exception & exception)  {
   std::cout << exception.what() << std::endl;

 return 0;

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