是一个常量字符串尽管如此preferable? [英] Is a const string Still Preferable?
问题描述
我问在这里的迭代器一个问题: preFER迭代超过指针我来了解一些保护和调试功能,它们的价格作为一个结果。
I asked a question on Iterators here: Prefer Iterators Over Pointers? I've come to understand some of the protection and debug capabilities they offer as a result.
不过,我相信, 开始
和 结束
现在提供的C数组类似的可能性。
However, I believe that begin
and end
now offer similar possibilities on C-style array.
如果我想创建一个常量字符串
只会在STL算法进行遍历,是仍然有一个优势,使用常量字符串
,或者我应该preFER 为const char [
]与开始
和结束
?
If I want to create a const string
that will only be iterated over in STL algorithms, is there still an advantage to using a const string
, or should I prefer const char[]
with begin
and end
?
推荐答案
因此,答案取决于对c什么版本++你使用
So the answer depends on what version of c++ you're using
由于C ++ 98没有 的std ::开始
或 的std ::结束
最好的举措就是接受你将不得不支付建设费用,并使用 STD: :字符串
。如果你有升压可你还是应该考虑 的boost :: string_ref
有两个原因。首先它的建设将始终避免分配,并且比的std ::字符串
。总要简单得多
Because C++98 doesn't have std::begin
or std::end
the best move is just to accept you're going to have to pay the costs of construction and use std::string
. If you have boost available you should still consider boost::string_ref
for two reasons. First its construction will always avoid allocation, and is overall much simpler than std::string
.
的boost :: string_ref
的作品,因为它只能存储一个指向字符串的长度。从而使得开销最小在所有情况下
boost::string_ref
works because it only stores a pointer to the string and the length. Thus the overhead is minimal in all cases.
非常类似于C ++ 98除了使用推荐的boost :: string_ref
变成 MUCH 更强,因为C ++ 11 constexpr
,允许编译器旁路建筑完全构建在编译时的对象。
Very similar to C++98 except the recommendation to use boost::string_ref
becomes MUCH stronger because c++11 has constexpr
which allows the compiler to bypass construction completely by constructing the object at compile time.
据说(这不是最后一次)的图书馆基础TS将会给我们带来 的std :: string_view
。 的boost :: string_ref
是一个原型的std :: string_view
的早期建议,旨在使功能C ++的某种形式的所有版本。
Allegedly (it's not final) the Library Fundamentals TS will be bringing us std::string_view
. boost::string_ref
was a prototype for an earlier proposal of std::string_view
and is designed to bring the functionality to all versions of C++ in some form.
C ++ 14引入的字符串与语法的 富S
可惜这仅仅是一个方便。因为运营商S
不是 constexpr
不能在编译时计算,因此不避刑罚建设带来的。因此,它可以被用来制造code更好看的,但它不提供在这种情况下,任何其他益处。
C++14 introduced string literals with the syntax "foo"s
unfortunately this is just a convenience. Because operator""s
is not constexpr
it cannot be evaluated at compile time and thus does not avoid the penalty that construction brings. So it can be used to make code nicer looking, but it doesn't provide any other benefit in this case.
这篇关于是一个常量字符串尽管如此preferable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!