Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c++ - stringstream->rdbuf()->pubsetbuf is not setting the buffer

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...