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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…