On 6/28/06, Evan Drumwright
Hi all,
I am having trouble with pointer ownership as a result of the const_cast operator. In particular, for the code below, when a const_cast is used to create a const int pointer, the use count for x does not increase. The result of this is that when x.pop_back() is called, y is no longer valid (though the use count for y remains 1).
Take a closer look at what this is doing:
boost::shared_ptr<const int> y(const_cast
(x.front().get()));
To be more explicit, it's the same as int *ip = x.front().get(); int const *cip = ip; boost::shared_ptr<const int> y( cip ); At y you're creasing another shared_ptr to the same address that doesn't share ownership with the one in x.front(). What you really want is const_pointer_cast : http://boost.org/libs/smart_ptr/shared_ptr.htm#const_pointer_cast
The documentation for shared_ptr does not help here. Any suggestions?
From the documentation for the above-mentioned const_pointer_cast: Notes: the seemingly equivalent expression shared_ptr<T>(const_cast
(r.get())) will eventually result in undefined behavior, attempting to delete the same object twice. Which is exactly your problem.
~ Scott McMurray