8

I am trying to modify a stringbuffer of a stringstream object without having to copy a string, using the method pubsetbuf, but it is not working. I am following the documentation in http://www.cplusplus.com/reference/iostream/streambuf/pubsetbuf/. Here is my example code:

#include <iostream>
#include <sstream>

int main(int argc, char* argv[])
{
    std::stringstream stream("You say goodbye");
    char replace[] = {"And I say hello"};
    std::cout << stream.str() << std::endl; // Checking original contents
    stream.rdbuf()->pubsetbuf(replace, 16); // Should set contents here
    std::cout << stream.str() << std::endl; // But don't :(
    return 0;
}

And the output is:

You say goodbye
You say goodbye

I know I can use stream.str(replace), but this method copies the value of 'replace', and I don't want to make a copy.

What am I missing?

Update: I'm using VS2010

  • 1
    just a ridiculously quick search of SO - are you experiencing this issue? http://stackoverflow.com/questions/1494182/setting-the-internal-buffer-used-by-a-standard-stream-pubsetbuf – im so confused Sep 18 '12 at 16:51
  • If you are using VS, have a look at [this question](http://stackoverflow.com/q/10054396/416627) (and answer). It doesn't work like you think it does. It's implementation defined and only implemented where it makes sense. – Dave Rager Sep 18 '12 at 17:03
  • Possible duplicate of [Setting the internal buffer used by a standard stream (pubsetbuf)](http://stackoverflow.com/questions/1494182/setting-the-internal-buffer-used-by-a-standard-stream-pubsetbuf) – Ciro Santilli OurBigBook.com Mar 30 '17 at 16:28

1 Answers1

11

Not should set contents. pubsetbuf calls virtual setbuf

basic_streambuf<charT,traits>* setbuf(charT* s, streamsize n);

15 Effects: implementation-defined, except that setbuf(0,0) has no effect.

16 Returns: this.

VS 2010. There is no overload of virtual method setbuf in basic_stringbuf, it uses default from basic_streambuf

virtual _Myt *__CLR_OR_THIS_CALL setbuf(_Elem *, streamsize)
    {   // offer buffer to external agent (do nothing)
    return (this);
    }
ForEveR
  • 55,233
  • 2
  • 119
  • 133
  • Thanks. I though that "specific implementations" in the documentation was referring to the concrete classes, not to specific vendor implementation. I presumed it would work well in any c++ compiler. – Flamínio Maranhão Sep 18 '12 at 19:16