assign new shared_pt object to a[1] , the reference count of the object original contained in a[1] decrease. How?

StackOverflow https://stackoverflow.com/questions/21827977

Question

In the code below, a[1] point to p1 first but then is assigned a new value p3. The reference count of the object pointed by p1 decreased to 1, which is correct behavior. But I just can not understand how it could be implemented. Is it done by the compiler?

int main()
{
    {
    cout << "1" << endl;
    std::tr1::shared_ptr<C>p0(new C(0)); 
    std::tr1::shared_ptr<C>p1(new C(1)); 

    std::tr1::shared_ptr<C> a[2];
    a[0]=p0;
    a[1]=p1;

    {
        cout << "p1 count" << p1.use_count() << endl;  // print 2
        std::tr1::shared_ptr<C>p3(new C(3));
        //p1 reference count decreased. how is it impelmented?
        a[1] = p3;
        cout << "p1 count" << p1.use_count() << endl; // print 1
    }

    }
}
Was it helpful?

Solution

The expression a[1] = p3 invokes the assignment operator of shared_ptr. This assignment operator will first decrement the reference counter of the object currently referenced and than increment the reference counter of the object newly referenced.

The reference counter is usually stored along with the reference object, not with the referencing smart pointer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top