Reputation:
I think that the the variable declared as const
applies only Static Initialization
. I've written the following:
#include <cstdlib>
#include <iostream>
struct A{ };
const A *i = new A();
int main(){ }
and it works fine.
But I expected that the the code is invalid because new A()
is a new-expression
and it is not a constant expression
. Actually:
sec. 5.19/2 N3797:
A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:
[...]
— a new-expression (5.3.4);[...]
and
A constant expression is either a glvalue core constant expression whose value refers to an object with static storage duration or to a function,
Upvotes: 1
Views: 68
Reputation: 171127
First off, you probably meant A * const i
(a constant pointer to A
) and not const A * i
(a non-constant pointer to const A
).
Still, even with this modification, it is perfectly legal to initialise a const
variable with a value that is not a constant expression (such as a value computed at runtime). However, it is then not possible to use such a variable inside constant expressions. If you tried that, the constant expression definition would kick in and you'd get an error.
Upvotes: 4
Reputation: 32202
The initialisation of a const
variable does not require a constant expression.
Upvotes: 0