临时和表达式行为 [英] Temporary and expression behavior
本文介绍了临时和表达式行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个定义好的行为吗?
const char* p = (std::string("Hello") + std::string("World")).c_str();
std::cout << p;
我不确定。原因?
推荐答案
不,这是未定义的行为。 std :: string
临时表和 operator
返回的临时表只有直到初始化 const char *
(完整表达式的结尾)。然后它们被销毁,并且 p
指向不确定的内存。
No, this is undefined behavior. Both std::string
temporaries and the temporary returned by operator+
only live until the end of the initialization of your const char*
(end of full expression). Then they are destroyed and p
points to uncertain memory.
这篇关于临时和表达式行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文