I'm currently using the very clever package boost::const_string
until http://libcxx.llvm.org/ is available pre-packaged on Ubuntu or GCC make its __versa_string
(in header ext/vstring.h
) its default string implementation. libcxx's std::string
aswell as __versa_string
uses _small-string optimization (SSO) by default. Default support for outputting to an std::ostream
is lacking however. The code
#include <iostream>
#include <boost/const_string.hpp>
const_string<char> x;
std::cout << x << endl;
does not work unless we force x
into a c-string via c_str()
which becomes
std::cout << x.c_str() << endl;
which compiles and works as expected. I added the following line to const_string.hpp
template <typename T>
inline std::ostream & operator << (std::ostream & os, const boost::const_string<T> & a)
{
return os.write(a.data(), a.size());
}
This should improve performance over x.c_str()
because size()
is already known and does not need to be calculated by searching for NULL
as in c_str()
. I works for me but I am uncertain whether it works all cases. Have I missed something?
Have I missed something?
Yes, just include const_string/io.hpp
. All it does however is:
return o << std::basic_string<char_type, traits_type>(s.data(), s.size());
It seems that this could have implications based on the locale and/or facets applied to the stream for strings vs just writing the straight data as you're doing.
It would be less performant, but what about creating a std::string from the const_string and using <<
to insert that into the stream?
No (you have not missed anything, afaik). If your aim is not to copy over content, str.data() is the way to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With