mardi 18 décembre 2018

Check whether an object derived from enable_shared_from_this is managed by shared_ptr?

Suppose I have a class derived from std::enable_shared_from_this

struct foo
  : std::enable_shared_from_this
{
    std::shared_ptr<foo> get_shared()
    {
        return shared_from_this();
    }

    bool is_shared() const
    {
        /* implementation ??? */
    }
};

foo A;
auto A=get_shared();   // UB (pre c++17) or exception (c++17)

Prior to c++17, there appears no way to detect whether an object foo is actually managed by a shared_ptr. Correct?

But even for c++17, I'm not sure how to best implement such a detection. One obvious approach is

bool foo::is_shared() const
{
    try {
        shared_from_this();
    } catch(...) { 
        return false;
    }
    return true;
}

But can the try-catch be avoided? Can I use weak_from_this? How?

Aucun commentaire:

Enregistrer un commentaire