vector of const pointers?
Solution 1
The vector is probably the only container that requires the elements to be copy assignable. This is because the elements are guaranteed to be stored contiguously in memory. So if you exceed the capacity, a new chunk has to be allocated and elements re-assigned. You cannot do this with const
elements.
Same error if you try std::vector<const int>
, or in fact any const
type.
Solution 2
You are declaring a vector that contain const
pointer of Foo, that mean that the pointer could not be modified. When you insert an element in the vector would need to write to a const pointer
(not valid).
You are sure it's not: std::vector<Foo const *> vec;
where Foo don't be modified by the pointer could.
Solution 3
Vector elements need to be assignable for many operations: If you insert an element in the middle of the vector, all the later elements have to be re-assigned. Const-qualified types are usually not assignable.
If you don't perform operations that require assignment, you can still use vectors of non-assignable types, though.
However, you may only use std::allocator<T>
when T
is a non-const object type, so std::vector<const int>
is ill-formed.
Solution 4
The C/C++ const
keyword is left-associative, i.e. it effects the token to its left, except if const
is the first token in a statement. So void *const
means "constant (=immutable) pointer to void".
Hence the semantics are:
int a;
void * const ptr = (void*)&a; /* legal */
int b;
ptr = (void*)&b; /* not permitted */
the later is illegal because const variables must be initialized at definition and can not be altered later on.
When writing std::vector<void * const>
you're asking the compiler to instance the template as a vector of immutable pointers to void. However immutable means, it can be assigned to only at definition, which however does not fly with the dynamic nature of std::vector
.
Agrim Pathak
Interests: Artificial Intelligence, Simulations Primary Languages: python, Ruby on Rails, C++, SQL
Updated on June 15, 2022Comments
-
Agrim Pathak almost 2 years
The following doesn't compile (very verbose error, but basically "cannot be overloaded" and "invalid conversion from 'const void*' to 'void*'"). I can understand why for example push_back() may not compile, as you can't copy/move into a
Foo* const
, but why doesn't this compile:#include <vector> using namespace std; class Foo; int main() { vector<Foo* const> vec; }