23

I was going through these two class implementations and found out that the strstream class is deprecated.

And if I use the stringstream class as replacement, then there is big difference between how they log in the buffer since the stringstream class object maintains a deep copy of the buffer.

Has anyone faced any problem while replacing strstream with stringstream class?

What would be the output of this code and why?

#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;


}
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
Soheb Khan
  • 231
  • 1
  • 2
  • 4

1 Answers1

15

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(); }
};
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380