Boost logo

Boost :

From: Raoul Gough (RaoulGough_at_[hidden])
Date: 2003-03-19 05:42:44


"Martin Bosticky" <mbosticky_at_[hidden]> wrote in message
news:35AD09302D3C9B44AC4102EC6B5CCBB71D3F33_at_EXCHANGE.aimltd.co.uk...
> Hi
>
> Me and my colleagues have come across an issue when using a
shared_ptr.
>
> void myFunction(shared_ptr<myClass> const & vp_Pointer)
> {
> vp_Pointer->call any non-const function
> }
>
> i.e. a const shared_ptr doesn't prevent anyone from changing the
> contents to which the pointer points. This makes sense as it behaves
> like a normal pointer.

That's the idea.

>
> However, how can I pass a shared pointer into a function such that
the
> data can not be modified? i.e. how can I pass an equivalent of
"myClass
> const *" ?
>
> I tried static casting to shared_ptr<const myClass> which works but
> causes a new constructor to be called which means I loose the
efficiency
> of passing by reference.

This would be the right way to do it.

>
> Any comments of suggestions would be greatly appreciated.

If you really have a performance problem here (so you're probably
counting processor cycles) you can always try reinterpret_cast :-)

shared_ptr<myClass> ptr (new myClass);
my_function (reinterpret_cast<shared_ptr<myClass const> &>(ptr));

Of course, this uses undefined behaviour, but it is reasonable to
assume that the const/non-const representations are actually
identical. I wouldn't do it myself, but then I don't have to count
processor cycles, either.

--
Raoul Gough
see http://home.clara.net/raoulgough/ for my work availability

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