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

问题描述

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

    

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 memorymaintained by the string object. It remains valid until a non-constfunction is called on the string object, or the string object isdestructed. The string object you're concerned about is a temporary.It will be destructed at the end of the full expression, not before andnot after. In your case, the end of the full expression is after thecall to consumer, so your code is safe. It wouldn't be if consumersaved 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'vewritten 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 affectany user written string class.)

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

08-20 08:58
查看更多