mercredi 28 décembre 2016

When should we use std::enable_shared_from_this

I just knew std::enable_shared_from_this form this link.
But after reading the code below, I don't know when to use it.

try {
        Good not_so_good;
        std::shared_ptr<Good> gp1 = not_so_good.getptr();
    } catch(std::bad_weak_ptr& e) {
        // undefined behavior (until C++17) and std::bad_weak_ptr thrown (since C++17)
        std::cout << e.what() << '\n';    
    }

The code above is "not so good" because there is no existing shared_ptr before calling getptr(). So the good thing should be:

std::shared_ptr<Good> gp1 = std::make_shared<Good>(); // having a shared_ptr at the beginning
std::shared_ptr<Good> gp2 = gp1->getptr();

However, if I have already had a shared_ptr object, why don't I just simply code like this: std::shared_ptr<Good> gp2 = gp1;, meaning that I don't need std::enable_shared_from_this at all.

In my opinion, using std::enable_shared_from_this is to make sure that more than one shared_ptr objects have the same control block. But if I must remind myself to create a shared_ptr at the beginning. Why don't I just remind myself to use shared_ptr object to create a new one, instead of using raw pointer?

Aucun commentaire:

Enregistrer un commentaire