EDIT: I'm not asking how to make the code work, but why it has error. Also, the static member is not only declared inside the class, but also has been initialized with a value (at least it appears to have), hence I don't think it's redundant. Also, this question asks beyond that, so please don't close it. It is not a duplicate.
Say class A
has a static member data defined inside. The shell record below does not link (ld: undefined reference).
Note that since C++11, std::vector<>::push_back() accepts either a const lvalue reference (const value_type&
) or an rvalue reference (value_type&& val
). Moreover, even if it doesn't accept an rvalue reference, an rvalue can be bound to a const lvalue reference.
$ cat class.h
struct A {
static const int STAT_MEMBER = 1;
A();
int a;
};
$ cat class.cc
#include "class.h"
#include <vector>
using namespace std;
A::A() { a = STAT_MEMBER; }
int main() {
vector<int> v;
v.push_back(A::STAT_MEMBER);
}
$ g++ -std=c++14 class.cc -o class
/tmp/ccNXDnyu.o: In function `main':
class.cc:(.text+0x2f): undefined reference to `A::STAT_MEMBER'
collect2: error: ld returned 1 exit status
$
Question:
(1) is A::STATIC_MEMBER
an rvalue? (but regardless of it being an rvalue or an lvalue, it shouldn't cause an error in linker -- it should have been fine or have caused an error in compiler)
(2) why didn't the compiler/linker complain about STATIC_MEMBER
in A::A()
?
(3) why didn't the compiler complain about STATIC_MEMBER
in main()
?
(4) why did the linker complain about STATIC_MEMBER
in main()
?
I know this problem should be gone if the static member is declared inside the class but defined outside the class, but I'm mostly interested the problem above.
G++ version: g++-6 (Ubuntu/Linaro 6.3.0-18ubuntu2~14.04) 6.3.0 20170519