Open utterances-bot opened 2 years ago
TL;DR std::enable_shared_from_this必须要public继承,否则调用shared_from_this()不会编译失败,但运行时会抛std::bad_weak_ptr的异常。
http://fuzhe1989.github.io/2021/07/25/cpp-enable-shared-from-this-must-be-public-inherited/
很好的角度,学到了,一直都是public,从未考虑过private,习惯没想为什么。
我特意看了下 cppreference ,开头的描述就说了 "Publicly inheriting from std::enable_shared_from_this provides the type T with a member function shared_from_this"。而且附带的示例的注释也强调 public inheritance, 不提private继承,那就说明必然是有坑的。
@kissingfire123 确实,主要是改老代码掉坑了。
[C++] 一定要 public 继承 std::enable_shared_from_this | Fu Zhe's Blog
TL;DR std::enable_shared_from_this必须要public继承,否则调用shared_from_this()不会编译失败,但运行时会抛std::bad_weak_ptr的异常。
http://fuzhe1989.github.io/2021/07/25/cpp-enable-shared-from-this-must-be-public-inherited/