I know that static literal type members can be initialized in the class definition, and non-literal types can't.
class Class
{
static const int lt = 0; //OK
static const std::string nlt = "hello"; //compilation error
};
However, I ran into a weird issue, where I can't use the members in STL containers if they are initialized inside the class definition, as opposed to outside.
class Class
{
public:
static const int var = 1;
void f();
};
void Class::f() {
std::vector<int> vec;
vec.push_back(var);
}
The example above results in the linker error undefined reference to Class::var
If I move the initialization outside, the error goes away.
const int Class::var = 1;
What are the differences between the two initializations above? Why does one cause the error with stl containers?
What are the differences between the two initializations above? Why does one cause the error with stl containers?
The argument type of std::vector<int>::push_back()
is int const&
. Whenever a variable is used by reference or pointer, it must be defined.
A simple change to Class::f
implementation will obviate the need to define Class::var
.
void Class::f() {
std::vector<int> vec;
int v = var;
vec.push_back(v);
}
Here, var
is not used by reference. Hence, there is no need to define Class::var
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments