c++pointersshared-ptrundefined-behaviorinvalid-pointer

undefined behaviour to use raw pointer from a deleted shared_ptr?


I have following code

#include <iostream>
#include <memory>
#include <cassert>

int main()
{
    void* p_any = nullptr;

    {
        auto  p_src = std::make_shared<int>(10); // new instance        
        p_any = p_src.get();                     // get raw unmanaged pointer?
        auto  p_again = reinterpret_cast<int*>(p_any);
        assert(*p_src == *p_again);
    }

    auto  p_again = reinterpret_cast<int*>(p_any); // ??
    std::cout << *p_again <<  "\n";                // undefined?, expected?

}

Are the last two statements safe?

I can run it http://cpp.sh/6poh with out put "10", but is it expected? or just a undefined behavior?


Solution

  • The p_src object goes out of scope with the closing brace, and since there's no other shared pointer instance the contained pointer will be deleted. So p_any will point to deleted data and you will indeed have undefined behavior.