Within the same unit, static variables get initialized in the order of their definitions.
So when you have the line:
LogLevel l = LogLevel::ERROR;
the variable LogLevel::ERROR
has not yet had its constructor run. This causes undefined behaviour. The reason this UB manifests itself as a segfault could be because you copy a std::string
by value which has not been initialized, so its internal pointer will be wild.
Reversing the order of the definitions fixes the problem, as then LogLevel::ERROR
does exist when you try and assign it to l
.
NB. It'd be preferable to make l
static
. This prevents you accidentally referring to it from another unit, so you avoid the static initialization order problem. If you intentionally want to refer to it from another unit, you'll have to make sure that you do not access it in that unit before main()
has been entered.