我目前正在使用非常聪明的包 boost::const_string
直到 http://libcxx.llvm.org/ 已在 Ubuntu 或 GCC 上预打包,使其 __versa_string(在标题中ext/vstring.h
)其默认字符串实现。 libcxx 的 std::string
以及 __versa_string
默认使用 _small-string 优化 (SSO)。然而,缺乏对输出到 std::ostream 的默认支持。 除非我们通过 c_str()
强制将 x
转换为 c 字符串,该代码
#include <iostream>
#include <boost/const_string.hpp>
const_string<char> x;
std::cout << x << endl;
才能
std::cout << x.c_str() << endl;
按预期编译和工作。我将以下行添加到 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());
}
这应该会提高 x.c_str()
的性能,因为 size()
已经已知并且不存在需要通过搜索 NULL
来计算,如 c_str()
中。我为我工作,但我不确定它是否适用于所有情况。我错过了什么吗?
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?
发布评论
评论(3)
不(你没有错过任何东西,据我所知)。如果您的目标不是复制内容,那么 str.data() 就是正确的选择。
No (you have not missed anything, afaik). If your aim is not to copy over content, str.data() is the way to go.
是的,只需包含
const_string/io.hpp
即可。然而它所做的只是:Yes, just include
const_string/io.hpp
. All it does however is:看起来,这可能会根据应用于字符串流的区域设置和/或方面与仅编写直接数据而产生影响。
这会降低性能,但是从 const_string 创建 std::string 并使用
<<
将其插入到流中怎么样?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?