Why is S::x not odr-used?

前端 未结 3 1264
难免孤独
难免孤独 2020-12-23 19:34

Consider this example from cppreference:

struct S { static const int x = 1; };
void f() { &S::x; } // discarded-value expression does not odr-use S::x
         


        
3条回答
  •  粉色の甜心
    2020-12-23 20:00

    When declaring const int, it may be entirely discarded by the compiler unless you using its address. taking the address is not enough.

    Discarded is not mean the value is not evaluated, it is, but it mean there is no memory address containing the const value, the compiler just replace the const variable by its value, as it was just a macro.

    In addition, when taking a pointer to it and taking back the value from the pointer, doesn't impress the compiler much, it just ignores it and use the value.

    The following code shows it, this code can be compiled and run (I test it by several compilers, I'm still not sure if it successfully compiled by all...) despite of the fact that S::x was not declared:

    #include 
    using namespace std;
    struct S
    {
        static const int x=0; 
    };
    //const int S::x; //discarded
    int main()
    {
        const int *px = &S::x;  //taking the address
        cout<< *px <

    But if I'll try to use the address itself(not the value) like:

    cout<< px <

    the link will failed dou to: "undefined reference to S::x".

    Therefore, my conclusion is: taking an address without using it, doesn't count at all.

提交回复
热议问题