User12547645
User12547645

Reputation: 8477

Why do is the content of a buffer deleted, when it reads an empty rdbuf?

Quick example (play with code):

int main() 
{
   
    std::stringstream sstr;
    sstr << "hello\n";
    sstr << "world\n";

    std::stringstream sstr2;
    // sstr2 << "test\n";
    if (sstr2.rdbuf()->in_avail() != 0)
    {    
        sstr << sstr2.rdbuf();
    }

    print_me(sstr);

    return 0;
}

I have a stream sstr. That stream holds data. I also want it to hold all other data that is stored in sstr2. For that I use sstr << sstr2.rdbuf();. If I execute that line when sstr2 is empty, then sstr will also be empty. Why is that?

PS: I know that I can protect myself from this scenario by using if (sstr2.rdbuf()->in_avail() != 0).

Upvotes: 0

Views: 96

Answers (1)

Farhad Sarvari
Farhad Sarvari

Reputation: 1081

If you want to preserve the old value you should use code like this :

sstr <<  sstr.rdbuf() << sstr2.rdbuf();

Upvotes: 1

Related Questions