Is taking the address of a local variable a constant expression in C++11?

前端 未结 6 1283
走了就别回头了
走了就别回头了 2021-02-07 06:13

The following C++11 program:

int x = 42;

void f()
{
        int y = 43;

        static_assert(&x < &y, "foo");
}

int main()
{
        f();         


        
6条回答
  •  独厮守ぢ
    2021-02-07 06:25

    In C++ pre-C++11:

    Other expressions [than integral constant expressions] are considered constantexpressions only for the purpose of nonlocal static object initialization (3.6.2). Such constant expressions shall evaluate to one of the following:

    [...]

    -- an address constant expression,

    [...]

    An address constant expression is a pointer to an lvalue designating an object of static storage duration, a string literal (2.13.4), or a function.

    Since y doesn't have static storage duration, &y would not be a constant expression.

    C++11 seems to have changed this; I suspect that this is an oversignt, however. (C++ pre-C++11 lists the things that are constant expressions. C++11 lists the things that aren't. It would be easy for one to have been forgotten.)

    Regardless, of course: your comparison isn't usable in standard C++; the results of comparing two addresses which don't point into the same object is unspecified. (On the other hand, I have occasionally used something similar in machine dependent code. Not statically, but on platforms like Linux on PC or Solaris, it's possible to determine whether a pointer points to an object with static lifetime, and auto variable, or dynamically allocated memory with such tricks.)

    EDIT:

    The answser by paxdiablo has quoted the passage I didn't find in my reading of C++11; C++11 follows the same rule as C++ pre-11 in this respect, and in order to be a constant address expression, the address must be that of an object with static lifetime (or a function, or a null pointer).

提交回复
热议问题