Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2007-07-23 21:16:22


Eric Niebler wrote:
> General design question here. This came up on the user's list, and it
> made me question something I believed to be true. When writing a proxy
> for, e.g., a std container, I see two options for handling const.
>
> 0) Const-ness depends on the const-ness of the object being proxied:
>
> struct vector_proxy {
> std::vector<int> & vec;
> typedef std::vector<int>::iterator iterator;
> typedef std::vector<int>::iterator const_iterator;
> iterator begin() const { return vec.begin(); }
> ...
> };
>
> 1) Const-ness depends on the proxy object itself:
>
> struct vector_proxy {
> std::vector<int> & vec;
> typedef std::vector<int>::iterator iterator;
> typedef std::vector<int>::const_iterator const_iterator;
> iterator begin() { return vec.begin(); }
> const_iterator begin() const { return vec.begin(); }
> ...
> };
>
> I think a loooong time ago, I preferred (1) but these days (0) is more
> natural for me, but I can't say why, exactly. Just feels like that's
> how it should be. Thoughts?

If the vector_proxy has an ordinary copy constructor, (0) is usually correct
because (1) cannot be enforced.

vector_proxy const a = ...;
vector_proxy b = a;

(1) typically only makes sense for types that are intended to be class
members and propagate the constness of the member function to the proxied
(referred to) object for some reason.

(1) can work for move-only types. I don't have experience with such proxies,
so I can't tell. :-)


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