std :: string :: c_str()和临时 [英] std::string::c_str() and temporaries

查看:155
本文介绍了std :: string :: c_str()和临时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下C ++代码格式正确:

  void consumer(char const * p)
{
std :: printf(%s,p);
}

std :: string random_string_generator()
{
//返回一个随机的std :: string对象
}

consumer(random_string_generator()。c_str());

我遇到的问题是,在创建临时std :: string对象后, c_str()指针,没有什么阻止std :: string对象被销毁(或者我错了?)。你能指点我的标准,如果代码是确定的,尽管一切。

std :: string: :c_str()指向由字符串对象维护的内存
。它一直有效,直到一个非const
函数调用字符串对象,或字符串对象是
销毁。你关心的字符串对象是一个临时的。
它将被破坏在完整表达式的结尾,而不是之前和
不在之后。在您的情况下,完整表达式的结尾是在
调用 consumer 之后,因此您的代码是安全的。这不是如果 consumer
将指针保存在某个地方,以后再使用它。



临时表的生命周期已经从C ++ 98中被严格定义。
在此之前,它有所不同,这取决于编译器,并且你
编写的代码不会使用g ++(1995年前,大致— g ++
)标准委员会投票赞成)。
(没有 std :: string 那么,但同样的问题影响
任何用户编写的字符串类。)


Is the following C++ code well-formed:

void consumer(char const* p)
{
  std::printf("%s", p);
}

std::string random_string_generator()
{
  // returns a random std::string object
}

consumer(random_string_generator().c_str());

The problem I have with it is, that after creating the temporary std::string object and taking the c_str() pointer, nothing prevents the std::string object from getting destroyed (or maybe I'm wrong?). Can you please point me to the standard, if the code is OK despite everything. It does work, when I test with g++.

解决方案

The pointer returned by std::string::c_str() points to memory maintained by the string object. It remains valid until a non-const function is called on the string object, or the string object is destructed. The string object you're concerned about is a temporary. It will be destructed at the end of the full expression, not before and not after. In your case, the end of the full expression is after the call to consumer, so your code is safe. It wouldn't be if consumer saved the pointer somewhere, with the idea of using it later.

The lifetime of temporaries has been strictly defined since C++98. Before that, it varied, depending on the compiler, and the code you've written wouldn't have worked with g++ (pre 1995, roughly—g++ changed this almost immediately when the standards committee voted it). (There wasn't an std::string then either, but the same issues affect any user written string class.)

这篇关于std :: string :: c_str()和临时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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