开发者

How can I get the same strstream functionality now that's deprecated?

I use to write code like this:

void fun(char *buff, unsigned si开发者_如何学运维ze)
{
    std::strstream str(buff, size);
    str << "hello world: " << 5;
}

so I can use stream output over an arbitrary buffer. I've found this technique both efficient (no allocations) and useful (streams!). Now that std::strstream is deprecated, how can I get the same speed+flexibility that I can get with this code?


The standard library doesn't provide that functionality. However, Boost does with its generic streams and array sources/sinks.

Boost Generic Stream
Boost Array Devices

char buff[size];
boost::stream<boost::array_sink> out(buff, size);
out << "Hello, world!";

(Code untested)


try:

#include <sstream>
std::stringstream str;
str << "hello world: " << 5;

Edit: Sorry, I think I over simplified your question. That functionality is one of the things removed when changing to sstream. Here is something similar (I think this works...):

#include <sstream>
void fun(char *buff, unsigned size)
{
    std::stringstream str;
    str << "hello world: " << 5;
    memcpy(buff, str.str().c_str(), size);
}


Now that std::strstream is deprecated, how can I get the same speed+flexibility that I can get with this code?

I think it was deprecated for a reason. I had numerous portability problems in past when dealing with case of stream reaching the end of the buffer. Lack of the unity probably triggered the deprecation in favor std::string using version.

Otherwise, it amuses me that you mention "speed" in context of iostreams and the "<<" operators. I did bunch of tests in past and iostreams simply cannot catch up with good ol' snprintf(). Making a function call for every element - the effect of "<<" operators - is taxing anyhow you look at it and would be always slower. That's the cost of strict type checks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜