Re: vector<const T(*)> vs. vector<T(*)>
On Oct 30, 12:04 pm, eiji.anonrem...@googlemail.com wrote:
I'm facing some uncertainty with const template arguments.
Maybe someone could explain the general strategy.
#include <vector>
int main(int arc, char** argv)
{
std::vector<const int> vec;
This is illegal---undefined behavior according to the standard.
It doesn't compile with my compiler (g++, with the usual
options). And whatever happens if it does compile, you can't
count on it.
const int i = 5;
vec.push_back(i);
vec[0] = 4; //const has gone away
Maybe. Or maybe it core dumps. Or maybe just about anything
else. (I would generally expect it not to compile, but the
standard doesn't require an error message.
std::vector<const int*> pvec;
const int* pi = new int(5);
pvec.push_back(pi);
*(pvec[0]) = 4; // not possible because const, compile error
return 0;
}
From the first impression, it is not possible to create a
vector of const ints. But you can do it with pointers.
What's in the vector cannot be const. You can create a vector
of non-const pointers to const (which is what you did), but not
of const pointers to anything. (You're probably being confused
by a widespread abuse of language. int const* is not a const
pointer, but a pointer to const. A const pointer would be int*
const or int const* const. More generally, just remember that
the const applies to whatever precedes it.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34