Boost logo

Boost Users :

From: me22 (me22.ca_at_[hidden])
Date: 2006-06-28 10:33:19


On 6/28/06, Evan Drumwright <edrumwri_at_[hidden]> wrote:
> 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<const int*>(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<T*>(r.get()))
> will eventually result in undefined behavior, attempting to delete the same object twice.
Which is exactly your problem.

~ Scott McMurray


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net