Search code examples
c++shared-ptrdouble-free

Shared pointers: why no double free?


Why does this code NOT generate a double free when the shared pointers go out of scope?

int main()
{
    {
        auto * ptr = new int(1);
        shared_ptr<int> a( ptr );
        shared_ptr<int> b( ptr );
        cout << "ok: " << *a << *b << endl;
    }
    cout << "still ok" << endl;
    return 0;
}

Solution

  • Why does this code NOT generate a double free when the shared pointers go out of scope?

    Why do you think it doesn't?

    It's undefined behavior, anything can happen. That includes your program printing out still ok.