Search code examples
c++shared-ptrsmart-pointers

Why does shared_ptr not delete its memory?


int main(){

    int* iptr;
    {
    std::shared_ptr<int> sptr = std::make_shared<int>(12);
    iptr = sptr.get();
    }

    std::cout << *iptr;

    return 0;
}

Output

12

I was expecting that the content to which iptr points, would have been deleted, at the end of inner curly braces. But output shows 12. Do I miss something?


Solution

  • Why does shared_ptr not delete its memory?

    shared_ptr does delete the memory that it owns when it is the last owner.

    I was expecting that the content to which iptr points, would have been deleted, at the end of inner curly braces.

    You were expecting correctly.

    But output shows 12. Do I miss something?

    You're missing that accessing through invalid pointers results in undefined behaviour.