22

我正在浏览这两个类的实现,发现strstream该类已被弃用。

如果我使用stringstream类作为替换,那么它们在缓冲区中的登录方式会有很大的不同,因为stringstream类对象维护着缓冲区的深层副本。

有人在替换类时遇到任何问题strstreamstringstream

这段代码的输出是什么,为什么?

#include<iostream>
#include <sstream>
#include <strstream>



int main(){

    char strArr[] = "Soheb Khan is great";

    char stringArr[] = "TurboCharging";

    std::strstream strStream(strArr,19);

    std::stringstream stringStream(std::string(stringArr,19));

    std::cout<<"Before Modification strArr= "<<strArr<<" & stringArr= "<<stringArr<<std::endl;

    strStream << "Fifa 2012 is nice";


    stringStream << "Sometimes its sucks";


    std::cout<<"After Modification strArr= "<<strArr<<" & stringArr= "<<stringArr<<std::endl;

    return 0;


}
4

1 回答 1

13

The classes from <strstream> are hideous to use. When they were more popular I haven't seen any correct production used (well, they got corrected when I spotted the problems). Either people didn't terminate the string using std::ends or they didn't release the memory using s.freeze(0) (or, most often, both). Although the <sstream> class do create a copy I haven't found this to be a problem.

In case memory allocation actually matters for your use case, either because you need to allocate large chunks or because you have many of them, you can take control easily and have data read from or written to buffers you provide using a custom stream buffer. For example, a stream buffer writing to a readily allocate chunk of memory is trivial to write:

struct omembuf
    : std::streambuf {
{
    omembuf(char* base, std::size_t size) {
        this->setp(base, base + size);
    }
    char* begin() const { return this->pbase(); }
    char* end() const { return this->pptr(); }
};
于 2012-12-15T15:04:38.300 回答