From: Martin Bosticky (mbosticky_at_[hidden])
Date: 2003-03-21 07:02:34
I have now added the following custom cast operator into my copy of
operator shared_ptr<const T>&()
return reinterpret_cast<shared_ptr<const T> &>(*this);
#endif // DARK_FORCE
and hence the following code compiles easily:
void Foo(boost::shared_ptr<const myClass> & vp_Param)
boost::shared_ptr<myClass> vl_MyTest_ptr(new myClass());
In theory I believe that the compiler should be able to perform the cast
from shared_ptr<myClass> to shared_ptr<const myClass> of it's accord as
easily as it should handle cast 'myClass*' to 'myClass const *'.
Apart from the fact that in theory this makes for undefined behaviour, I
suspect that since all shared_ptr code is in headers and the only
difference between the classes is the 'const', there is actually no
practical difference between them and hence it is safe.
Only possibility to worry about I think could be the multithreaded
Can anyone device a code that would fail with such DARK_FORCE operator?
From: Raoul Gough [mailto:RaoulGough_at_[hidden]]
Sent: 19 March 2003 10:43
Subject: [boost] Re: Safety of shared_ptr
"Martin Bosticky" <mbosticky_at_[hidden]> wrote in message
> Me and my colleagues have come across an issue when using a
> 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
> data can not be modified? i.e. how can I pass an equivalent of
> 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
> 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 _______________________________________________ Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk