There are several interesting questions on pitfalls with boost::shared_ptrs. In one of them, there is the useful tip to avoid pointing boost::shared_ptr<Base> and boost::shared_ptr<Derived> to the same object of type Derived since they use different reference counts and might destroy the object prematurely.
My question: Is it safe to have both boost::shared_ptr<T> and boost::shared_ptr<const T> point to the same object of type T, or will this cause the same problem?
It is perfectly safe.
The following code sample:
Compiles and run fine, and is perfectly correct. It outputs:
The two
shared_ptrshare the same reference counter.Also:
Behave the same way. You must, however never build your
shared_ptrusing a construct like this:a.get()gives the raw pointer and loses all information about reference counting. Doing this, you’ll end up with two distinct (not linked)shared_ptrthat use the same pointer but different reference counters.