问题描述
我测试过这段代码:
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int main()
{
string s1("a"),s2("b");
const char * s = (s1+s2).c_str();
printf("%s\n",s);
}
返回ab。
据我所知,由于(s1 + s2)
是一个临时对象,可能会以某种方式消失(我不知道),然后 const char * s
可能指向未定义的内存并可能被转储。
As far as I know, since (s1 +s2)
is a temporary object and may disappear somehow (I have no idea about that), then const char * s
may point to undefined memory and may get dumped.
$ c> .c_str()这样吗?
So is it safe to use the .c_str()
like that?
推荐答案
printf("%s\n", (a + b).c_str());
原因是临时值(类似于 a + b
)在完整表达式的末尾被销毁。在你的例子中, const char *
在包含临时和解除引用的完整表达式中存活,是未定义的行为。
The reason is that temporary values (like the result of a + b
) are destroyed at the end of the full expression. In your example the const char *
survives the full expression containing the temporary and dereferencing it is undefined behaviour.
未定义的行为的最坏的部分是,事情可能显然工作反正...(UB代码崩溃,只有如果你在包括你的父母的广大观众面前演示);
The worst part of "undefined behaviour" is that things may apparently work anyway... (UB code crashes only if you're making your demo in front of a vast audience that includes your parents ;-) )
这篇关于是否可以安全使用(str1 + str2).c_str()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!