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

前端 未结 6 1282
走了就别回头了
走了就别回头了 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:16

    Taking the address of something is not the culprit here, but rather the pointer comparison using operator< on unrelated objects.

    Relational operators on pointers is only specified for pointers to objects within the same class or within an array (5.9 Relational operators [expr.rel], points 3 and 4.) Relational comparison for pointers to unrelated objects is unspecified.

    Comparing the address for equality rather than ordering does work:

    int x = 42;
    
    void f()
    {
            int y = 43;
    
            static_assert(&x != &y, "foo");
                             ^^ <--- "<" on unrelated objects is unspecified
    }
    
    int main()
    {
            f();
    }
    

    Live example

    Just to show that this has nothing to do with const-expressions per se,

    void f()
    {
            int y[2] = { 42, 43 };
    
            static_assert(&y[0] < &y[1], "foo");
                                ^ <--- "<" on objects within an array is specified
    }
    
    int main()
    {
            f();
    }
    

    Another live example.

提交回复
热议问题