I was playing around for a bit using the shared_ptr's and enable_shared_from_this, while I run into something I don't really understand.
In my first attempt I constructed something like this:
class shared_test : std::enable_shared_from_this<shared_test> {
public:
void print(bool recursive) {
if (recursive) {
shared_from_this()->print(false);
}
std::cout << "printing" << std::endl;
}
};
Please note that this class is extending std::enable_shared_from_this privately. This apparently makes a lot of difference because executing a something like this:
int main() {
auto t(std::make_shared<shared_test>());
t->print(true);
return 0;
}
throws an bad_weak_ptr exception. Where as if I change the class definition to inherent publicly from std::enable_shared_from_this this runs just find.
Why is that, what do I miss here? And isn't there a way to make it work for private inheritance, since the 'outside world' of the shared_test class does not need to know that it is enabling shared from this... (at least, not if you ask me, or do I miss something again?)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…