(I was asked this question recently.)
I want to use the C++ static_block construct to initialize static
field of a class:
static_block {
myns::foo my_foo;
auto s = my_foo.from_string("null");
if (s.good()) {
std::string bar::transmogrified_foo = my_foo.transmogrify();
} else {
std::string bar::transmogrified_foo = "";
}
}
where transmogrified_foo is declared in the class as:
static std::string transmogrified_foo;
However, I get the following error:
error: definition or redeclaration of 'transmogrified_foo' not allowed inside a function
Do you have suggestion how the static field should be initialized ?
You're confusing the definition of the static member with its initialization. See also:
The differences between initialize, define, declare a variable
It seems like you were trying to define your static field, when it has no other definition. Indeed, you can't do that within the body of a function (and a
static_blockactually invokes a static function).You could do one of two things:
I would go with option (2.) :
So, you see the static block doesn't really give you any benefit here.