我最近发现std::strstream有人不赞成使用std::stringstream.自从我使用它已经有一段时间了,但它确实做了我当时需要做的事情,所以听到它的弃用感到惊讶.
我的问题是为什么做出这个决定,以及没有std::stringstream提供哪些好处std::strstream?
我在清理旧C/C++应用程序的调试宏时遇到了这个问题:我们有一个继承自的Tracer类ostrstream(我知道它自C++ 98以来已被弃用,但这个应用程序是在1998年编写的!)我们使用它像这样:
Tracer() << "some" << " message" << " here";
Run Code Online (Sandbox Code Playgroud)
现在,如果链中的第一个值是上面的常量字符串,则调用ostrstream::str()Tracer 的结果(在析构函数中完成,将结果插入到队列中)包含指向此字符串的指针的十六进制表示,而不是文本.因此,上述陈述会产生类似的结果"0x401a37 message here".旧宏不会发生这种情况,因为它们总是有一个长(线程ID)作为现在已被删除的第一个值.
使用gdb进入它会显示,对于第一次插入,这将调用operator<<(void const*)ostrstream,而后续插入调用operator<< <...>(basic_ostream<...>&, char const*)(为了可读性而移除了模板).
有人可以解释这种行为吗?什么是一个干净的方法来解决这个问题?我找到了一个简单的解决方法,它<< left用作第一个参数 - 这样安全吗?有没有更好的方法来做到这一点?
这是一个最小化的例子:
#include <strstream>
#include <iostream>
using namespace std;
class Trace : public ostrstream {
public:
Trace();
virtual ~Trace();
};
Trace::Trace() : ostrstream() {}
Trace::~Trace() {
static_cast< ostrstream& >(*this) <<ends;
char * text = ostrstream::str();
cout << "MESSAGE: "<< text <<endl;
delete[] text;
}
int …Run Code Online (Sandbox Code Playgroud) <spanstream>将在 C++23 中首次亮相(请参阅cppreference)。根据提案,它们是std::span基于缓冲区的字符串流。
我的问题是:
std::spanstream与旧的std::strstream(或strstream在 C++ 98 中已弃用)有些等效?