[C++-sig] why does the "shared_ptr<X> const&" silently become 0xCCCCCCCC

athor thorena at gmail.com
Thu Mar 12 13:36:16 CET 2009

zaexage wrote:
> I got a  'class Manager' which contains a std::set of shared_ptr<Entity>;
> and  'class Entity'  has a auto_ptr<StateMachine> as member
> and  'class StateMachine'  needs shared_ptr<Entity> as member variable to
> access some functions outside.
> So, in order to break cyclic reference, I make the StateMachine to own a
> 'shared_ptr<Entity> const&', I think it's kind of reasonable.

I also use VS2008 with Python 2.5 and the boost libraries using the boost
consulting installer so it seems identical (which is strange).

I'd guess there's a simple typo somewhere. By using a const& to the
shared_ptr, it may be deallocated once the program (Python/C++) thinks the
original shared_ptr is not in use anymore. For example, 
a = A()
a = B(a)
would be such a simple typo. A would immediately be deallocated but the
const ref in B wouldn't know.

A few comments:

* I assume each entity owns a unique StateMachine. Otherwise, the
auto_ptr<StateMachine> may be a problem. I've had many strange bugs from
using auto_ptr and thus I only use shared_ptr nowadays.

* You don't *need* a const& to break cyclic reference. Passing a shared_ptr
by value works too.
// Forward Declare Entity
class Entity;

// Declare StateMachine
class StateMachine
StateMachine(shared_ptr<Entity> e) {...}

// Declare Entitity
class Entity
Entity(shared_ptr<StateMachine> s) {...}

View this message in context: http://www.nabble.com/why-does-the-%22shared_ptr%3CX%3E-const-%22-silently-become-0xCCCCCCCC-tp22449314p22475430.html
Sent from the Python - c++-sig mailing list archive at Nabble.com.

More information about the Cplusplus-sig mailing list