Should I preallocate std::stringstream?

后端 未结 4 808
终归单人心
终归单人心 2020-12-16 10:39

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

4条回答
  •  执念已碎
    2020-12-16 11:16

    Although "mucking around with the stringstream's rdbuf...is probably Very Easy To Get Wrong", I went ahead and hacked together a proof-of-concept anyway for fun, as it has always bugged me that there is no easy way to reserve storage for stringstream. Again, as @luke said, you are probably better off optimizing what your profiler tells you needs optimizing, so this is just to address "What if I want to do it anyway?".

    Instead of mucking around with stringstream's rdbuf, I made my own, which does pretty much the same thing. It implements only the minimum, and uses a string as a buffer. Don't ask me why I called it a VECTOR_output_stream. This is just a quickly-hacked-together thing.

    constexpr auto preallocated_size = 256;
    auto stream = vector_output_stream(preallocated_size);
    stream << "My parrot ate " << 3 << " cookies.";
    cout << stream.str() << endl;
    

提交回复
热议问题