Boost logo

Boost Users :

From: Scott McCaskill (scott_at_[hidden])
Date: 2003-12-12 08:40:18


>
>
> Hi,
>
> Just out of curiosity. I am increasingly using the smart_ptr and more
> specifically the shared_ptr but I came to realize that actually it rather
> violently breaches the constness rules. The example below is
> one of the many things you can do with a shared pointer that is forbidden
> with a naked pointer. As the shared_ptr penetrates even further in my
> code I come to realize that what I am gaining on the comfort side
> I loose on the safety. Clearly, that's my call but I was curious to know
> if it is a known fact that it is impossible to enforce constness rules.
>
> Cyril Godart
> Quantitative Analyst
> BNP Paribas.
>
>
>
> struct A
> {
> int bar;
> };
> typedef boost::shared_ptr<A> A_ptr_t;
> void foo(const A_ptr_t& a)
> {
> a->bar++;//semantically this should not be possible.
> }
> int main(int argc, char* argv[])
> {
> A_ptr_t a(new A);
> a->bar = 1;
> foo(a);
>
> return 0;
> }
>

In this situation, I believe you need to use a shared_ptr<const A> to get
the behavior you want. Think of the difference between A const* (or const
A* if you prefer) and A* const. The latter is analagous to your use of
shared_ptr in the example above (const pointer to non-const object).

Scott McCaskill


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