1

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.

Ideone

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,

2 Answers2

4

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.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
  • Does it mean that const variables does not require a Static Initialization? –  Jun 30 '14 at 11:33
  • @DmitryFucintv Yes, that's what I meant. *Some* `const` variables can also be constant expressions, but they don't have to. That's one of the reasons why C++11 introduced `constexpr`. – Angew is no longer proud of SO Jun 30 '14 at 11:36
0

The initialisation of a const variable does not require a constant expression.

filmor
  • 30,840
  • 6
  • 50
  • 48