stringstream :: str复制生命周期 [英] stringstream::str copy lifetime
问题描述
第一次使用 stringstream
时,许多C ++程序员错过了(读取:me)是由 stringstream :: str()
是一个临时的,它持续到它使用的表达式的结尾。但是,我不明白:
Something a lot of C++ programmers miss (read: me) when first using stringstream
s is the fact that the copy returned by stringstream::str()
is a temporary, which lasts until the end of the expression it's used in. However, I don't understand:
- 如何做。查看libstdc ++的
sstream
头文件,我只看到一个副本被创建和返回。 - 为什么这是期望的行为,特别是因为它是一个常见的秘密。如果正在发送副本,为什么我不能拥有该副本?
- How this is done. Looking in the
sstream
header for libstdc++, I only see a copy being made and returned. How is the lifetime restricted? - Why this is the desired behavior, especially since it is such a common gotcha. If a copy is being made anyway, why can't I take ownership of it?
请注意,这不是< a href =http://stackoverflow.com/questions/1374468/c-stringstream-string-and-char-conversion-confusion> C ++ stringstream,string和char *转换混淆。这解释了行为和解决方法;我正在寻找机制和理由。
Note that this is not a duplicate of C++ stringstream, string, and char* conversion confusion. That goes over explaining the behavior and workarounds; I'm looking for mechanics and rationale.
推荐答案
这不是 stringstream
。这是 c_str
函数的问题 - 它返回指向 char *
表示的指针 std :: string
,但它只在原始字符串的生命周期内存在。当你调用 char * str = ss.str()。c_str()
时,会发生以下情况:
This is not a problem of stringstream
. It is the problem of c_str
function - it returns pointer to a char*
representation of std::string
, but it lives only during lifetime of an original string. When you call char *str = ss.str().c_str()
the following actually happens:
string tmp = ss.str();
char *str = tmp.c_str();
tmp.~string (); // after that line the pointer `str` is no longer valid
c_str
是一个危险的功能,仅为兼容性和速度的目的,您应避免使用它。
c_str
is a dangerous function provided only for compatibility and speed purposes and you should avoid using it.
这篇关于stringstream :: str复制生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!