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;
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
add a comment |
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
add a comment |
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
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
c++ shared-ptr weak-ptr private-inheritance enable-shared-from-this
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
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
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.
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 callingshared_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. Thestd::shared_ptr
constructor has no mechanism to tell whether you made a mistake by privately inheriting fromstd::enable_shared_from_this
or whether you just privately inherited from some class that publicly inherited fromstd::enable_shared_from_this
. Theshared_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 withstd::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 fromstd::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 ownweak_ptr
and maintain it yourself.
– curiousguy
2 hours ago
add a comment |
You have to publicly inherit from std::enable_shared_from_this
in order for it to work.
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
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 callingshared_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. Thestd::shared_ptr
constructor has no mechanism to tell whether you made a mistake by privately inheriting fromstd::enable_shared_from_this
or whether you just privately inherited from some class that publicly inherited fromstd::enable_shared_from_this
. Theshared_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 withstd::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 fromstd::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 ownweak_ptr
and maintain it yourself.
– curiousguy
2 hours ago
add a comment |
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.
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 callingshared_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. Thestd::shared_ptr
constructor has no mechanism to tell whether you made a mistake by privately inheriting fromstd::enable_shared_from_this
or whether you just privately inherited from some class that publicly inherited fromstd::enable_shared_from_this
. Theshared_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 withstd::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 fromstd::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 ownweak_ptr
and maintain it yourself.
– curiousguy
2 hours ago
add a comment |
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.
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.
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 callingshared_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. Thestd::shared_ptr
constructor has no mechanism to tell whether you made a mistake by privately inheriting fromstd::enable_shared_from_this
or whether you just privately inherited from some class that publicly inherited fromstd::enable_shared_from_this
. Theshared_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 withstd::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 fromstd::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 ownweak_ptr
and maintain it yourself.
– curiousguy
2 hours ago
add a comment |
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 callingshared_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. Thestd::shared_ptr
constructor has no mechanism to tell whether you made a mistake by privately inheriting fromstd::enable_shared_from_this
or whether you just privately inherited from some class that publicly inherited fromstd::enable_shared_from_this
. Theshared_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 withstd::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 fromstd::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 ownweak_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
add a comment |
You have to publicly inherit from std::enable_shared_from_this
in order for it to work.
add a comment |
You have to publicly inherit from std::enable_shared_from_this
in order for it to work.
add a comment |
You have to publicly inherit from std::enable_shared_from_this
in order for it to work.
You have to publicly inherit from std::enable_shared_from_this
in order for it to work.
answered 8 hours ago
NathanOliverNathanOliver
108k19 gold badges161 silver badges240 bronze badges
108k19 gold badges161 silver badges240 bronze badges
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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