简体   繁体   中英

Returning a shared pointer from a weak pointer return type

Is this safe to do? Why is my IDE warning me about it?

std::weak_ptr<SomeClass> getStatus() 
{
    return _mStatus;
}
private:
std::shared_ptr<SomeClass> _mStatus = std::make_shared<SomeClass>();

My IDE states:

Returning std::shared_ptr<SomeClass> from a function returning std::weak_ptr<SomeClass> . Class std::shared_ptr<SomeClass> is not compatible with class std::weak_ptr<SomeClass>

Is this safe or not? Should I ignore this warning? I get a crash somewhere here and I am thinking this might be a cause.

Your IDE is wrong; the code is fine. There is an implicit conversion from shared_ptr to weak_ptr ; returning a shared_ptr from a function whose return type is weak_ptr will just call the conversion. I just tested your code with three different compilers (gcc 8.3, msvc 2019, xcode 10) and they all made the conversion with no warnings. Returning a weak_ptr is perfectly safe because it will automatically become null if the original shared_ptr goes away, there's no danger of a dangling pointer here.

The error message seems to imply that your compiler believes the conversion is invalid; maybe you're using a very old version of the standard library? I don't remember whether there was ever a draft version of weak_ptr where the conversion from shared_ptr was explicit or required a function call.

My understanding is that while the shared_ptr does reference counting, the weak_ptr doesn't. So, whether this is safe depends on how you are using it. The risk is that you return a weak_ptr to _mStatus and then the owning object (that has the shared_ptr reference to it) goes away, causing the ref-count to be zero and therefore the memory is freed but your weak_ptr reference to it is now referring to free'd memory causing chaos. Now, weak_ptr has a protection that if you get the value from it and it has already been free'd it will give you a newly init'ed pointer (ie a null pointer). But, if your caller is getting the weak_ptr and getting the pointer value from it (perhaps copying off to a primitive pointer type) and then the owning object goes away then that raw pointer value is now bogus.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM