Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enable_shared_from_this (c++0x): what am I doing wrong?

I'm just toying around with the smart pointers in the upcoming new c++ standard. However I fail to grasp the usage of the shared_from_this function. Here is what I have:

#include <iostream>
#include <memory>

class CVerboseBornAndDie2 : public std::enable_shared_from_this<CVerboseBornAndDie2>
{
public:
    std::string m_Name;
    CVerboseBornAndDie2(std::string name) : m_Name(name)
    {
        std::cout << m_Name << " (" <<  this << ") is born!" << std::endl;
    }
    virtual ~CVerboseBornAndDie2()
    {
        std::cout << m_Name << " (" <<  this << ") is dying!" << std::endl;
    }
};

int main(){
    CVerboseBornAndDie2* vbad = new CVerboseBornAndDie2("foo");
    std::shared_ptr<CVerboseBornAndDie2> p = vbad->shared_from_this();
}

and it throws a std::bad_weak_ptr exception in the line

std::shared_ptr<CVerboseBornAndDie2> p = vbad->shared_from_this();

if I instead do

std::shared_ptr<CVerboseBornAndDie2> p(vbad);

it works and I can afterwards do

std::shared_ptr<CVerboseBornAndDie2> p2 = p.get()->shared_from_this();

so must the object belong to one shared_ptr before I can use shared_from_this? But how can I know this beforehand?

like image 805
fschmitt Avatar asked Dec 13 '10 10:12

fschmitt


People also ask

How enable_ shared_ from_ this works?

std::enable_shared_from_this is a standard solution that enables a shared_ptr managed object to acquire a shared_ptr to itself on demand. A class T that publicly inherits an std::enable_shared_from_this<T> encapsulates a std::weak_ptr<T> to itself that can be converted to a std::shared_ptr<T> when needed.

What is shared_ from_ this in c++?

std::shared_ptr and shared_from_this The C++ standard gets around this issue via the function shared_from_this , which safely creates shared pointers to this without duplicate control blocks.


1 Answers

It is a precondition of using shared_from_this that there must exist at least one shared_ptr which owns the object in question. This means that you can only use shared_from_this to retrieve a shared_ptr that owns an object to which you have a reference or pointer, you cannot use it to find out if such an object is owned by a shared_ptr.

You need to rework your design so that either you are guaranteed that any such object is being managed by a shared_ptr or that you don't ever need to know or finally (and least desirably) you create some other way of managing this knowledge.

like image 100
CB Bailey Avatar answered Sep 20 '22 04:09

CB Bailey