串联字符串文字上的c_str()安全吗? [英] Is c_str() on a concatenated string literal safe?

查看:91
本文介绍了串联字符串文字上的c_str()安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从此答案知道,字符串文字是静态分配的。但是以下字符串串联是否也可以安全使用?

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());
}

关注问题:如评论中所述,当functionTakingCString存储该指针时,这确实是不安全的。在这种情况下,以下内容是否有效:

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());
}


推荐答案

只分配了连接字符串在 functionTakingCString(( start + foo + end)。c_str()); 运行的同时。然后将内存释放,并且指针不再安全使用,因为您可以在此处阅读。如果该指针传递给 functionTakingCString 退出后运行的任何内容,那么您将遇到麻烦。

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.

这篇关于串联字符串文字上的c_str()安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆