Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking address of a static member C++ FAQ

Tags:

c++

What does this C++ FAQ try to convey ?

You can take the address of a static member if (and only if) it has an out-of-class definition :

class AE {
    // ...
public:
    static const int c6 = 7;
    static const int c7 = 31;
};

const int AE::c7;   // definition

int f()
{
    const int* p1 = &AE::c6;    // error: c6 not an lvalue
    const int* p2 = &AE::c7;    // ok
    // ...
}

However this compiles !

like image 744
P0W Avatar asked Jun 19 '14 08:06

P0W


1 Answers

You use -O2 to compile. The compiler can optimize away the const int* p1 = &AE::c6; assignment (as it has no effect) and therefore it does not need the address of AE::c6 in the final code, that's why it compiles.

It gives a linker error without optimization.

You also get a linker error if you start to use p1 (e.g. std::cout << p1 << p2 << std::endl;) Link

like image 163
Csq Avatar answered Oct 01 '22 15:10

Csq