Boost logo

Boost :

Subject: Re: [boost] [Pointer Container] Modification of pointer containers to allow const elements
From: Scott McMurray (me22.ca+boost_at_[hidden])
Date: 2010-10-15 14:50:36


2010/10/15 Gerardo Hernández <g.hernandez_at_[hidden]>:
>
> My point was to allow ptr containers of <const T> to work, maintaining
> const-correctness. I believe that requires different underlying
> container types and not only one as you suggest. So in this code
> snippet:
>
> boost::ptr_vector<const int> v;
>
> v.push_back(new int);
> v[0] = 3;
>
> the assignment shall produce a compiler error as v[0] would be const,
> to maintain const-correctness.
>

That will still work with using internal containers that are always
void const *.

ptr_vector<T>'s operator[] would become something like this:
    T &operator[](size_type i) {
        return *const_cast<T*>(static_cast<T const *>(internal_container[i]));
    }

That way if T is int const, it's returning an int const& -- and the
const_cast is a NOP -- which will prevent v[0] = 3; as desired, but if
T is non-const int, then it's returning an int& -- and the const_cast
is a type conversion from int const* to int* that's legal because the
invariant of the pointer container means that the pointer was of that
type on insert, as inserters like push_back don't accept int const* in
ptr_vector<int>, just like how we know that the static_cast is legal
because of the invariant.

Was that clearer?

~ Scott


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