临时和表达行为
这是明确定义的行为吗?
const char* p = (std::string("Hello") + std::string("World")).c_str();
std::cout << p;
我不知道。原因?
Is this well defined behavior?
const char* p = (std::string("Hello") + std::string("World")).c_str();
std::cout << p;
I am not sure. Reasons?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,这是未定义的行为。
std::string
临时变量和operator+
返回的临时变量都只能存活到const char*
初始化结束(完整的结束)表达)。然后它们被销毁并且p
指向不确定的内存。No, this is undefined behavior. Both
std::string
temporaries and the temporary returned byoperator+
only live until the end of the initialization of yourconst char*
(end of full expression). Then they are destroyed andp
points to uncertain memory.否,行为未定义,因为
p
指向std::cout << 中已释放的存储空间。 p;
创建一个临时对象来保存
std::string("Hello") + std::string("World")
。然后从该对象中检索 C 样式字符串。在表达式末尾,临时对象被销毁,留下p
指向已释放的存储空间。然后使用
p
调用未定义的行为。12.2/4 说
No the behaviour is undefined because
p
points to deallocated storage instd::cout << p;
A temporary is created to hold
std::string("Hello") + std::string("World")
. C-style string is then retrived from that object. At the end of the expression that temporary is destroyed leavingp
pointing to a deallocated storage.Using
p
then invokes Undefined Behavior.12.2/4 says
由于缺少分号,它不会编译:
现在规则适用,临时值在其使用的表达式末尾(分号处)被删除。所以你有一个指向已删除内存的指针,这会导致未定义的行为。
it won't compile because of a missing semi-colon:
NOW the rule applies that the temporary is deleted at the end of the expression it is used in, which is at the semicolon. So you have a pointer to deleted memory which causes undefined behaviour.
我最近读了这本优秀的书 http://www.amazon.co.uk/Gotchas-Avoiding-Addison-Wesley-Professional-Computing/dp/0321125185/ref 如果我没记错的话,这几乎是给出的示例之一那里。
我相信从
c_str
返回的数据仅在返回它的字符串对象有效时才有效。示例中的字符串对象仅在表达式的持续时间内有效。I recently read this excellent book http://www.amazon.co.uk/Gotchas-Avoiding-Addison-Wesley-Professional-Computing/dp/0321125185/ref and if I recall correctly this is pretty much one of the examples given there.
I believe the data returned from
c_str
is only valid as long as the string object that returned it is live. The string objects in your example are only live for the duration of the expression.