Trivial cases of shared_ptr and weak_ptr failingstd::enable_shared_from_this; public vs privateIs there any advantage of using map over unordered_map in case of trivial keys?shared_ptr and weak_ptr differencesWhen is std::weak_ptr useful?Difference in make_shared and normal shared_ptr in C++shared_ptr, weak_ptr and circular dependenciesCleaning data after exception on class constructorHow does shared_ptr<T> detect that T derives from enable_shared_from_this<T>?Crash when destroying weak_ptr, double destruction of weak_ptr's shared_ptr_emplace objectenable shared from this crashAssigning shared_ptr to weak_ptr

Can a pizza stone be fixed after soap has been used to clean it?

Sending a photo of my bank account card to the future employer

What could be reasoning of male prison in VR world to only allow undershirt and sarong as nightwear to male prisoners

Why do candidates not quit if they no longer have a realistic chance to win in the 2020 US presidents election

Construct, in some manner, a four-dimensional "RegionPlot"

Is this artwork (used in a video game) real?

How to say no to more work as a PhD student so I can graduate

Snaking a clogged tub drain

Cine footage fron Saturn V launch's

Did 007 exist before James Bond?

FPGA CPU's, how to find the max speed?

What are "full piece" and "half piece" in chess?

Do dragons smell of lilacs?

What is the meaning of [[:space:]] in bash?

how many bits in the resultant hash will change, if the x bits are changed in its the original input

Why does FFmpeg choose 10+20+20 ms instead of an even 16 ms for 60 fps GIF images?

Cauchy reals and Dedekind reals satisfy "the same mathematical theorems"

Can "plane" (aeroplane) be used as a non-count noun?

How should one refer to knights (& dames) in academic writing?

What happens when I team swap while I have Pokemon inside a gym?

Why should I cook the flour first when making bechamel sauce?

What "fuel more powerful than anything the West (had) in stock" put Laika in orbit aboard Sputnik 2?

What made Windows ME so crash-prone?

Unix chat server making communication between terminals possible



Trivial cases of shared_ptr and weak_ptr failing


std::enable_shared_from_this; public vs privateIs there any advantage of using map over unordered_map in case of trivial keys?shared_ptr and weak_ptr differencesWhen is std::weak_ptr useful?Difference in make_shared and normal shared_ptr in C++shared_ptr, weak_ptr and circular dependenciesCleaning data after exception on class constructorHow does shared_ptr<T> detect that T derives from enable_shared_from_this<T>?Crash when destroying weak_ptr, double destruction of weak_ptr's shared_ptr_emplace objectenable shared from this crashAssigning shared_ptr to weak_ptr






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








10















I'm having trouble using shared_ptr and weak_ptr along with enable_shared_from_this.



When I google the symptoms of what I'm seeing, everybody suggests "you cannot use shared_from_this() when there are no shared_ptr instances owning your object.



But that's not my case.



Consider this code:



#include <memory>
#include <cassert>

class MyClass : std::enable_shared_from_this<MyClass>

public:
void this_fails()

// Doesn't even assert(), because it throws bad_weak_ptr
assert(shared_from_this());

void this_fails_too()

std::weak_ptr<MyClass> weak = weak_from_this();
std::shared_ptr<MyClass> strong = weak.lock();
// This assert fails
assert(strong.get());

;

int main()

std::shared_ptr<MyClass> obj = std::make_shared<MyClass>();

obj->this_fails();
obj->this_fails_too();




Both methods in MyClass crash the program. I must be missing something obvious - what is it?










share|improve this question






























    10















    I'm having trouble using shared_ptr and weak_ptr along with enable_shared_from_this.



    When I google the symptoms of what I'm seeing, everybody suggests "you cannot use shared_from_this() when there are no shared_ptr instances owning your object.



    But that's not my case.



    Consider this code:



    #include <memory>
    #include <cassert>

    class MyClass : std::enable_shared_from_this<MyClass>

    public:
    void this_fails()

    // Doesn't even assert(), because it throws bad_weak_ptr
    assert(shared_from_this());

    void this_fails_too()

    std::weak_ptr<MyClass> weak = weak_from_this();
    std::shared_ptr<MyClass> strong = weak.lock();
    // This assert fails
    assert(strong.get());

    ;

    int main()

    std::shared_ptr<MyClass> obj = std::make_shared<MyClass>();

    obj->this_fails();
    obj->this_fails_too();




    Both methods in MyClass crash the program. I must be missing something obvious - what is it?










    share|improve this question


























      10












      10








      10








      I'm having trouble using shared_ptr and weak_ptr along with enable_shared_from_this.



      When I google the symptoms of what I'm seeing, everybody suggests "you cannot use shared_from_this() when there are no shared_ptr instances owning your object.



      But that's not my case.



      Consider this code:



      #include <memory>
      #include <cassert>

      class MyClass : std::enable_shared_from_this<MyClass>

      public:
      void this_fails()

      // Doesn't even assert(), because it throws bad_weak_ptr
      assert(shared_from_this());

      void this_fails_too()

      std::weak_ptr<MyClass> weak = weak_from_this();
      std::shared_ptr<MyClass> strong = weak.lock();
      // This assert fails
      assert(strong.get());

      ;

      int main()

      std::shared_ptr<MyClass> obj = std::make_shared<MyClass>();

      obj->this_fails();
      obj->this_fails_too();




      Both methods in MyClass crash the program. I must be missing something obvious - what is it?










      share|improve this question
















      I'm having trouble using shared_ptr and weak_ptr along with enable_shared_from_this.



      When I google the symptoms of what I'm seeing, everybody suggests "you cannot use shared_from_this() when there are no shared_ptr instances owning your object.



      But that's not my case.



      Consider this code:



      #include <memory>
      #include <cassert>

      class MyClass : std::enable_shared_from_this<MyClass>

      public:
      void this_fails()

      // Doesn't even assert(), because it throws bad_weak_ptr
      assert(shared_from_this());

      void this_fails_too()

      std::weak_ptr<MyClass> weak = weak_from_this();
      std::shared_ptr<MyClass> strong = weak.lock();
      // This assert fails
      assert(strong.get());

      ;

      int main()

      std::shared_ptr<MyClass> obj = std::make_shared<MyClass>();

      obj->this_fails();
      obj->this_fails_too();




      Both methods in MyClass crash the program. I must be missing something obvious - what is it?







      c++ shared-ptr weak-ptr private-inheritance enable-shared-from-this






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 3 hours ago









      curiousguy

      5,0292 gold badges30 silver badges46 bronze badges




      5,0292 gold badges30 silver badges46 bronze badges










      asked 8 hours ago









      LubosDLubosD

      3231 silver badge12 bronze badges




      3231 silver badge12 bronze badges






















          2 Answers
          2






          active

          oldest

          votes


















          11














          You must inherit publicly from std::enable_shared_from_this. Inheriting privately doesn't help - std::shared_ptr can't access the base class and set it up properly.






          share|improve this answer


















          • 1





            That must be the one of the most counter-intuitive behaviors I have seen. Why doesn't it cause compile time errors? -- Explanation is here: stackoverflow.com/questions/39937112/…

            – LubosD
            8 hours ago












          • @LubosD I don't see why you would expect a compiler error. From the compilers point of view, inheriting privately is fine and calling shared_from_this is fine. That it doesn't give the desired run-time behaviour is not the compilers problem. The code is well formed C++ regardless of whether it gives you the expected behaviour or not.

            – Jesper Juhl
            8 hours ago






          • 1





            @LubosD There is no easy way to give a compile error. The std::shared_ptr constructor has no mechanism to tell whether you made a mistake by privately inheriting from std::enable_shared_from_this or whether you just privately inherited from some class that publicly inherited from std::enable_shared_from_this. The shared_from_this function has no way of knowing the most derived class type so it also cannot detect the programmer's error.

            – Brian
            8 hours ago











          • Well, the standard could mandate checking for base with std::is_base_of, and then complaining if it is ambiguous or inaccessible.

            – Deduplicator
            7 hours ago











          • @LubosD What's counter intuitive is that a class isn't required to derive from std::enable_shared_from_this but something will occur only if it does. This is very dirty and will not work if you allocate another class that uses membership instead of inheritance. Just have your own weak_ptr and maintain it yourself.

            – curiousguy
            2 hours ago


















          10














          You have to publicly inherit from std::enable_shared_from_this in order for it to work.






          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57064277%2ftrivial-cases-of-shared-ptr-and-weak-ptr-failing%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            11














            You must inherit publicly from std::enable_shared_from_this. Inheriting privately doesn't help - std::shared_ptr can't access the base class and set it up properly.






            share|improve this answer


















            • 1





              That must be the one of the most counter-intuitive behaviors I have seen. Why doesn't it cause compile time errors? -- Explanation is here: stackoverflow.com/questions/39937112/…

              – LubosD
              8 hours ago












            • @LubosD I don't see why you would expect a compiler error. From the compilers point of view, inheriting privately is fine and calling shared_from_this is fine. That it doesn't give the desired run-time behaviour is not the compilers problem. The code is well formed C++ regardless of whether it gives you the expected behaviour or not.

              – Jesper Juhl
              8 hours ago






            • 1





              @LubosD There is no easy way to give a compile error. The std::shared_ptr constructor has no mechanism to tell whether you made a mistake by privately inheriting from std::enable_shared_from_this or whether you just privately inherited from some class that publicly inherited from std::enable_shared_from_this. The shared_from_this function has no way of knowing the most derived class type so it also cannot detect the programmer's error.

              – Brian
              8 hours ago











            • Well, the standard could mandate checking for base with std::is_base_of, and then complaining if it is ambiguous or inaccessible.

              – Deduplicator
              7 hours ago











            • @LubosD What's counter intuitive is that a class isn't required to derive from std::enable_shared_from_this but something will occur only if it does. This is very dirty and will not work if you allocate another class that uses membership instead of inheritance. Just have your own weak_ptr and maintain it yourself.

              – curiousguy
              2 hours ago















            11














            You must inherit publicly from std::enable_shared_from_this. Inheriting privately doesn't help - std::shared_ptr can't access the base class and set it up properly.






            share|improve this answer


















            • 1





              That must be the one of the most counter-intuitive behaviors I have seen. Why doesn't it cause compile time errors? -- Explanation is here: stackoverflow.com/questions/39937112/…

              – LubosD
              8 hours ago












            • @LubosD I don't see why you would expect a compiler error. From the compilers point of view, inheriting privately is fine and calling shared_from_this is fine. That it doesn't give the desired run-time behaviour is not the compilers problem. The code is well formed C++ regardless of whether it gives you the expected behaviour or not.

              – Jesper Juhl
              8 hours ago






            • 1





              @LubosD There is no easy way to give a compile error. The std::shared_ptr constructor has no mechanism to tell whether you made a mistake by privately inheriting from std::enable_shared_from_this or whether you just privately inherited from some class that publicly inherited from std::enable_shared_from_this. The shared_from_this function has no way of knowing the most derived class type so it also cannot detect the programmer's error.

              – Brian
              8 hours ago











            • Well, the standard could mandate checking for base with std::is_base_of, and then complaining if it is ambiguous or inaccessible.

              – Deduplicator
              7 hours ago











            • @LubosD What's counter intuitive is that a class isn't required to derive from std::enable_shared_from_this but something will occur only if it does. This is very dirty and will not work if you allocate another class that uses membership instead of inheritance. Just have your own weak_ptr and maintain it yourself.

              – curiousguy
              2 hours ago













            11












            11








            11







            You must inherit publicly from std::enable_shared_from_this. Inheriting privately doesn't help - std::shared_ptr can't access the base class and set it up properly.






            share|improve this answer













            You must inherit publicly from std::enable_shared_from_this. Inheriting privately doesn't help - std::shared_ptr can't access the base class and set it up properly.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 8 hours ago









            Igor TandetnikIgor Tandetnik

            35.4k3 gold badges38 silver badges61 bronze badges




            35.4k3 gold badges38 silver badges61 bronze badges







            • 1





              That must be the one of the most counter-intuitive behaviors I have seen. Why doesn't it cause compile time errors? -- Explanation is here: stackoverflow.com/questions/39937112/…

              – LubosD
              8 hours ago












            • @LubosD I don't see why you would expect a compiler error. From the compilers point of view, inheriting privately is fine and calling shared_from_this is fine. That it doesn't give the desired run-time behaviour is not the compilers problem. The code is well formed C++ regardless of whether it gives you the expected behaviour or not.

              – Jesper Juhl
              8 hours ago






            • 1





              @LubosD There is no easy way to give a compile error. The std::shared_ptr constructor has no mechanism to tell whether you made a mistake by privately inheriting from std::enable_shared_from_this or whether you just privately inherited from some class that publicly inherited from std::enable_shared_from_this. The shared_from_this function has no way of knowing the most derived class type so it also cannot detect the programmer's error.

              – Brian
              8 hours ago











            • Well, the standard could mandate checking for base with std::is_base_of, and then complaining if it is ambiguous or inaccessible.

              – Deduplicator
              7 hours ago











            • @LubosD What's counter intuitive is that a class isn't required to derive from std::enable_shared_from_this but something will occur only if it does. This is very dirty and will not work if you allocate another class that uses membership instead of inheritance. Just have your own weak_ptr and maintain it yourself.

              – curiousguy
              2 hours ago












            • 1





              That must be the one of the most counter-intuitive behaviors I have seen. Why doesn't it cause compile time errors? -- Explanation is here: stackoverflow.com/questions/39937112/…

              – LubosD
              8 hours ago












            • @LubosD I don't see why you would expect a compiler error. From the compilers point of view, inheriting privately is fine and calling shared_from_this is fine. That it doesn't give the desired run-time behaviour is not the compilers problem. The code is well formed C++ regardless of whether it gives you the expected behaviour or not.

              – Jesper Juhl
              8 hours ago






            • 1





              @LubosD There is no easy way to give a compile error. The std::shared_ptr constructor has no mechanism to tell whether you made a mistake by privately inheriting from std::enable_shared_from_this or whether you just privately inherited from some class that publicly inherited from std::enable_shared_from_this. The shared_from_this function has no way of knowing the most derived class type so it also cannot detect the programmer's error.

              – Brian
              8 hours ago











            • Well, the standard could mandate checking for base with std::is_base_of, and then complaining if it is ambiguous or inaccessible.

              – Deduplicator
              7 hours ago











            • @LubosD What's counter intuitive is that a class isn't required to derive from std::enable_shared_from_this but something will occur only if it does. This is very dirty and will not work if you allocate another class that uses membership instead of inheritance. Just have your own weak_ptr and maintain it yourself.

              – curiousguy
              2 hours ago







            1




            1





            That must be the one of the most counter-intuitive behaviors I have seen. Why doesn't it cause compile time errors? -- Explanation is here: stackoverflow.com/questions/39937112/…

            – LubosD
            8 hours ago






            That must be the one of the most counter-intuitive behaviors I have seen. Why doesn't it cause compile time errors? -- Explanation is here: stackoverflow.com/questions/39937112/…

            – LubosD
            8 hours ago














            @LubosD I don't see why you would expect a compiler error. From the compilers point of view, inheriting privately is fine and calling shared_from_this is fine. That it doesn't give the desired run-time behaviour is not the compilers problem. The code is well formed C++ regardless of whether it gives you the expected behaviour or not.

            – Jesper Juhl
            8 hours ago





            @LubosD I don't see why you would expect a compiler error. From the compilers point of view, inheriting privately is fine and calling shared_from_this is fine. That it doesn't give the desired run-time behaviour is not the compilers problem. The code is well formed C++ regardless of whether it gives you the expected behaviour or not.

            – Jesper Juhl
            8 hours ago




            1




            1





            @LubosD There is no easy way to give a compile error. The std::shared_ptr constructor has no mechanism to tell whether you made a mistake by privately inheriting from std::enable_shared_from_this or whether you just privately inherited from some class that publicly inherited from std::enable_shared_from_this. The shared_from_this function has no way of knowing the most derived class type so it also cannot detect the programmer's error.

            – Brian
            8 hours ago





            @LubosD There is no easy way to give a compile error. The std::shared_ptr constructor has no mechanism to tell whether you made a mistake by privately inheriting from std::enable_shared_from_this or whether you just privately inherited from some class that publicly inherited from std::enable_shared_from_this. The shared_from_this function has no way of knowing the most derived class type so it also cannot detect the programmer's error.

            – Brian
            8 hours ago













            Well, the standard could mandate checking for base with std::is_base_of, and then complaining if it is ambiguous or inaccessible.

            – Deduplicator
            7 hours ago





            Well, the standard could mandate checking for base with std::is_base_of, and then complaining if it is ambiguous or inaccessible.

            – Deduplicator
            7 hours ago













            @LubosD What's counter intuitive is that a class isn't required to derive from std::enable_shared_from_this but something will occur only if it does. This is very dirty and will not work if you allocate another class that uses membership instead of inheritance. Just have your own weak_ptr and maintain it yourself.

            – curiousguy
            2 hours ago





            @LubosD What's counter intuitive is that a class isn't required to derive from std::enable_shared_from_this but something will occur only if it does. This is very dirty and will not work if you allocate another class that uses membership instead of inheritance. Just have your own weak_ptr and maintain it yourself.

            – curiousguy
            2 hours ago













            10














            You have to publicly inherit from std::enable_shared_from_this in order for it to work.






            share|improve this answer



























              10














              You have to publicly inherit from std::enable_shared_from_this in order for it to work.






              share|improve this answer

























                10












                10








                10







                You have to publicly inherit from std::enable_shared_from_this in order for it to work.






                share|improve this answer













                You have to publicly inherit from std::enable_shared_from_this in order for it to work.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 8 hours ago









                NathanOliverNathanOliver

                108k19 gold badges161 silver badges240 bronze badges




                108k19 gold badges161 silver badges240 bronze badges



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57064277%2ftrivial-cases-of-shared-ptr-and-weak-ptr-failing%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                    Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                    199年 目錄 大件事 到箇年出世嗰人 到箇年死嗰人 節慶、風俗習慣 導覽選單