问题
I know from this answer that string literals are allocated statically. But is the following string concatenation also safe to use?
void someFunction(std::string& foo) {
functionTakingCString(("start " + foo + " end").c_str());
}
Follow Up Question: As stated in the comments, this would be indeed unsafe when functionTakingCString would store that pointer. In this case, would the following be valid:
void someFunction(std::string& foo) {
std::string bar = "start " + foo + " end";
functionTakingCString(bar.c_str());
}
回答1:
The concatenated string is only allocated while functionTakingCString(("start " + foo + " end").c_str());
is running. Then the memory is deallocated and that pointer is no longer safe to use as you can read here. If that pointer is passed to anything that runs after functionTakingCString
exits then you will have trouble.
来源:https://stackoverflow.com/questions/34873395/is-c-str-on-a-concatenated-string-literal-safe