gpt4 book ai didi

c++ - 在 std::ostrstream::str 之后使用 std::ostrstream::freeze 以防止内存泄漏

转载 作者:太空狗 更新时间:2023-10-29 21:41:24 26 4
gpt4 key购买 nike

http://en.cppreference.com/w/cpp/io/ostrstream/freeze

Notes After a call to str(), dynamic streams become frozen automatically. A call to freeze(false) is required before exiting the scope in which this ostrstream object was created. otherwise the destructor will leak memory. Also, additional output to a frozen stream may be truncated once it reaches the end of the allocated buffer.

std::string Function( const ObjectA & obj )
{
std::ostringstream os;
os << obj;

return os.str( );
}

问题> 此函数是否由于在 str() 之后缺少对 std::ostrstream::freeze 的调用而导致内存泄漏?

最佳答案

该标准有效地解释了(D.7.1.1 和 D.7.1.2 部分)str()设置 strstream 的状态冷冻,然后strstreambuf::~strstreambuf()

frees the dynamically allocated array object only if strmode & allocated != 0 and strmode & frozen == 0.

作为您的 strstream (考虑到你的问题,我假设这里使用 stringstream 是一个错字)是一个本地对象,当你返回时它被销毁,内存泄漏。

重要说明: strstream已弃用并仅出于兼容性问题而保持事件状态。如果你使用 stringstream你不会泄漏 stringstream::str() 使用字符串

关于c++ - 在 std::ostrstream::str 之后使用 std::ostrstream::freeze 以防止内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28950575/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com