Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shared pointer and raw pointer lifetime

Could someone explain simply the reason why this does not work:

std::shared_pointer<Bar> getSharedPointer() {
    return std::make_shared<Bar>();
}

...

auto foo = getSharedPointer().get();

Apparently using the raw pointer foo will cause a segfault because the lifetime of the shared pointer returned by getSharedPointer() will have run out. Somehow I would expect it to last until the end of its scope (like whatever block it is inside).

Is this correct and are there any analogous examples to this situation?

like image 292
tau Avatar asked Oct 15 '25 17:10

tau


1 Answers

For getSharedPointer().get();, getSharedPointer() returns a temporary std::shared_ptr which will be destroyed after the expression immediately, and the pointer managed by it will be deleted too. After that foo will become dangled, any dereference on it causes UB.

auto foo = getSharedPointer().get();
// foo have become dangled from here

You could use a named variable instead:

auto spb = getSharedPointer();
auto foo = spb.get();
// It's fine to use foo now, but still need to note its lifetime
// because spb will be destroyed when get out of its scope
// and the pointer being managed will be deleted too
like image 163
songyuanyao Avatar answered Oct 18 '25 06:10

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!