views:

425

answers:

3

I use std::stringstream extensively to construct strings and error messages in my application. The stringstreams are usually very short life automatic variables.

Will such usage cause heap reallocation for every variable?

Should I switch from temporary to class-member stringstream variable?

In latter case how can I reserve stringstream buffer (init it with large enough string or there's more elegant method?)?

Thanks.

+5  A: 

Have you profiled your execution, and found them to be a source of slow down?

Consider their usage. Are they mostly for error messages outside the normal flow of your code?

As far as reserving space...

Some implementations probably reserve a small buffer before any allocation takes place for the stringstream. Many implementations of std::string do this.

Another option might be (untested!)

std::string str;
str.reserve(50);
std::stringstream sstr(str);

You might find some more ideas in this gamedev thread.

edit:

Mucking around with the stringstream's rdbuf might also be a solution. This approach is probably Very Easy To Get Wrong though, so please be sure it's absolutely necessary. Definitely not elegant or concise.

luke
A: 

More elegant?
We have not seen your current code, but from the simple description above it seems fine.

Martin York
A: 

I think you want strstream, which was superseded by stringstream because of safety issues. However, prefer safety over efficiency when possible. Be careful for future-safeness too: strstream is deprecated.

stefaanv