35 lines · plain
1.. title:: clang-tidy - bugprone-incorrect-enable-shared-from-this2 3bugprone-incorrect-enable-shared-from-this4==========================================5 6Detect classes or structs that do not publicly inherit from7``std::enable_shared_from_this``, because unintended behavior will8otherwise occur when calling ``shared_from_this``.9 10Consider the following code:11 12.. code-block:: c++13 14 #include <memory>15 16 // private inheritance17 class BadExample : std::enable_shared_from_this<BadExample> {18 19 // ``shared_from_this``` unintended behaviour20 // `libstdc++` implementation returns uninitialized ``weak_ptr``21 public:22 BadExample* foo() { return shared_from_this().get(); }23 void bar() { return; }24 };25 26 void using_not_public() {27 auto bad_example = std::make_shared<BadExample>();28 auto* b_ex = bad_example->foo();29 b_ex->bar();30 }31 32Using `libstdc++` implementation, ``shared_from_this`` will throw33``std::bad_weak_ptr``. When ``using_not_public()`` is called, this code will34crash without exception handling.35