Boost logo

Boost :

From: Thomas Maeder (maeder_at_[hidden])
Date: 2001-05-16 02:29:45


This problem report is a result of a discussion in
news://newsgroups.borland.com/borland.public.cppbuilder.language

The following program demonstrates it, using boost 1.21.1 and gcc 2.95.3:

#include <iostream>

#include "boost/smart_ptr.hpp"

struct S
{
    ~S()
    {
      std::cout << "~S()\n";
    }
    
    boost::shared_ptr<S> next;
};

int main()
{
  boost::shared_ptr<S> head(new S);
  head->next.reset(new S);
  std::cout << "before assignment\n";
  head = head->next;
  std::cout << "after assignment\n";
}

The output is

before assginment
~S()
~S()
after assginment

while one would expect it to be

before assignment
~S()
after assignment
~S()

The reason is that the shared_ptr copy-assignment operator first reduces the
reference count of the previously owned object and only then increases that
of the newly owned object; if both objects are the same, strange things
happen.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk