Does erasing a shared_ptr from a set deletes the managed object

92 views Asked by At

In the following code, I expect the memory that pointer tr points, to be destroyed. However even though I verified sp1, points to the same address with tr, and clearing the set causes the trial object sp kept to be destroyed, tr still points to the same address and the trial object it shows is not destroyed, according to gdb, at the line return 0.

class trial
:public enable_shared_from_this<trial>
{
public:
    trial(int n)
    {
        cout<<"new trial created with number : " << n << endl;
        a = (int*)malloc(4);
        *a = n;
    }


    ~trial() {
        cout << "trial destroyed"<< endl;
    }

    int *a;
};

int main() {
    cout << "Program Started" << endl;

    trial *tr = new trial(5);
    shared_ptr<trial> sp1(tr);
    set<shared_ptr<trial>> trialVector;

    trialVector.insert(std::move(sp1));


    trialVector.clear();

    return 0;
}

When the program arrives to the line of return 0, console shows this :

Program Started
new trial created with number : 5
trial destroyed

acknowledging that, tr is indeed destroyed, once sp1 is removed from the set. But tr has still the same address and the same value.

What is going on here?

Edit: For clarity, my question is this:

Shouldn't the content of the address the pointer tr shows should be erased, once the last shared_ptr pointing to the manager object which points to the adress of pointer tr , is destructed upon being erased from the set ?

2

There are 2 answers

3
riodoro1 On BEST ANSWER

After the object is destroyed tr becomes a dangling pointer or the pointer to released memory. Why would the value in tr change if it is just a separate variable which happens to hold address to some point in memory?

0
Steephen On

If you try following debug code it will be evident that shared_ptr sp1 has reference count is zero after std::vector::clear() call.

trialVector.clear();
std::cout<<sp1.use_count();