开发者

Address of static const isn't const expression?

I though address-of-static was a constant expres开发者_开发百科sion as in the example below but I get a compiler error (or is this new to C++0x?)

class X {
    static const int x;
    enum { y = &x };
};


Address of a variable (be it static or non-static) is not a compile-time constant. enum requires compile-time constant. That is why that is giving error.

In fact, GCC gives very clear error message:

prog.cpp:7: error: ‘X::x’ cannot appear in a constant-expression
prog.cpp:7: error: `&' cannot appear in a constant-expression

See yourself : http://ideone.com/FJk3C


However, the following is allowed:

class X {
    static const int x;
    enum { y = sizeof(x) }; //okay. sizeof(x) can be known at compile time!
};

Don't confuse compile-time constants with runtime constants. They're two different things.


Reading the 1998 standard, 5.19(1): "In several places, C++ requires expressions that evaluate to an integral or enumeration constant...as enumerator initializers (7.2)...."

Further, "An integral constant-expression can involve only....In particular, except in sizeof expressions, functions, class objects, pointers, or references shall not be used...."

Floating literals are explicitly listed as castable to integral or enumeration type, and nothing else is.

Casting even an address constant expression to make an enumerator initializer was invalid from the first standard.


It's a constant expression, but it can't be determined at compile time. The actual value of the address will depend on the region of memory that the executable ends up being loaded to by whatever OS loader is running the thing. Enum members need to have values that can be determined by the compiler.

Cheers,
J.


The address of a static object is a constant expression, but it's not an integral constant expression, because it doesn't have an integral type. And reinterpret_casting it to an integral type still doesn't make it an integral constant expression, since reinterpret_cast isn't allowed in integral constant expressions. And the initializer for an enum value requires an integral constant expression.

As it stands, of course, the reason you're getting a compiler error is that you're trying to initialize an enum value with an expression that doesn't have an integral type, and doesn't have an implicit conversion to an integral type.


The program is ill-formed because:

  • the address of an object is not a integral constant expression
  • taking the address of x requires a(n out of class) definition
  • using a static const integral member anywhere except where an integral constant-expression is required requires a definition.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜