Why initializing a std::string
to ""
(through lambda) crashes?
This will not crash:
static std::string strTest2 =
[](){std::string * s = &strTest2; (*s) = "a"; return s->c_str();}();`
This trick (initialize it to non empty first, but the intended final value is empty) will not crash:
static std::string strTest3 =
[](){std::string * s = &strTest3; (*s) = "b"; (*s) = ""; return s->c_str();}();
CRASHES here at (*s) = ""
. Is it because it is an empty string? Is it special? Is the std::string
not constructed/initialized when assigning to ""
?
static std::string strTest1 =
[](){std::string * s = &strTest1; (*s) = ""; return s->c_str();}();`
All of these are undefined behavior. The fact that some of them don't cause a crash is irrelevant; they're all nonsensical code. Some of them happen to "work" for you. This time.
All of them are UB for the same reason: you're accessing an object before it gets initialized. strTest
cannot legally be accessed in the expression used to initialize it. Which is precisely what your lambda attempts to do.
Why that particular one crashes on your compiler and build settings and the others don't doesn't matter. None of them represent valid C++ code.