Re: Containers of pointers and const-correctness
Alf P. Steinbach wrote:
* Stuart Golodetz:
#include <vector>
struct B {};
struct D1 : B {};
struct D2 : B {};
int main()
{
std::vector<D1*> vD1;
// Doesn't compile (shouldn't)
//std::vector<B*>& vB = vD1;
// Doesn't compile (shouldn't)
//std::vector<const D1*>& vCD1C = vD1;
// Doesn't compile (but why would it be a bad thing if it did?)
const std::vector<const D1*>& CvCD1 = vD1;
return 0;
}
Assume the vector has 1 element, which is a pointer.
A reference to a vector of 1 element is (with respect to what counts
here) functionally equivalent to a pointer to a vector of 1 element,
which is functionally equivalent to a pointer to a pointer.
So you're asking why you can't do
T* p = ...
T** pp = &p;
T const** PP = pp;
It would break const correctness, allowing you to modify an original
const thing.
See the FAQ item titled "Why am I getting an error converting a Foo** to
const Foo**", currently 18.17 and available at e.g. <url:
http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.17>.
I've seen that actually (I've been hanging around in this newsgroup for
a while, so read the FAQ quite a few times!), but thanks for the link
:-) I did wonder whether/how that might be an issue here. I got as far
as thinking:
std::vector<int*> v;
&v[0] is of type int **
const std::vector<const int*>
&v[0] is of type const int **
Hence the problem (which seems an implementation detail problem rather
than an LSP-related one). But is there any reason why operator[]
couldn't return a const pointer (i.e. the actual pointer is const)? In
that case, the type in the first case would be int *const *, and in the
second would be const int *const *. Would the original problem still
exist in that case?
There is, however, also another issue hinted at by your code, having to
do with upcast/downcast of a collection.
The answer for that other issue is that the standard library containers
do not support all that they in principle could support within type safety.
Ok, fair enough. I don't suppose anyone's suggested augmenting them in a
future revision of the standard? Or is that not a Pandora's box which
anyone particularly wants to open, since it probably doesn't bother
large numbers of people? :-)
Cheers,
Stu
Cheers & hth.,
- Alf