Is c_str() on a concatenated string literal safe?

为君一笑 提交于 2019-12-11 10:14:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!