From my understanding, const modifiers should be read from right to left. From that, I get that:
const char*
is a pointer whose char elements can’t be modified, but the pointer itself can, and
char const*
is a constant pointer to mutable chars.
But I get the following errors for the following code:
const char* x = new char[20];
x = new char[30]; //this works, as expected
x[0] = 'a'; //gives an error as expected
char const* y = new char[20];
y = new char[20]; //this works, although the pointer should be const (right?)
y[0] = 'a'; //this doesn't although I expect it to work
So… which one is it? Is my understanding or my compiler(VS 2005) wrong?
Actually, according to the standard,
constmodifies the element directly to its left. The use ofconstat the beginning of a declaration is just a convenient mental shortcut. So the following two statements are equivalent:In order to ensure the pointer itself is not modified,
constshould be placed after the asterisk:To protect both the pointer and the content to which it points, use two consts.
I’ve personally adopted always putting the const after the portion I intend not to modify such that I maintain consistency even when the pointer is the part I wish to keep constant.