SO 文档中的字符串主题曾经说过,在备注部分:
Since C++14, instead of using
"foo"
, it is recommended to use"foo"s
, ass
is a string literal, which converts theconst char *
"foo"
tostd::string
"foo"
.
我看到的唯一优势
std::string str = "foo"s;
而不是
std::string str = "foo";
是在第一种情况下编译器可以执行复制省略(我认为),这会比第二种情况下的构造函数调用更快。
尽管如此,这是(尚未)保证的,所以第一个也可能调用构造函数,即复制构造函数。
忽略 需要 使用 std::string
文字的情况,如
std::string str = "Hello "s + "World!"s;
使用 std::string
文字代替 const char[]
文字有什么好处吗?
最佳答案
如果您是“几乎总是自动”人群中的一员,那么 UDL 就非常重要。它可以让你这样做:
auto str = "Foo"s;
因此,str
会是正品std::string
,而不是 const char*
.因此,它允许您决定何时执行哪个操作。
这对于自动返回类型推导也很重要:
[]() {return "Foo"s;}
或者任何形式的类型推导,真的:
template<typename T>
void foo(T &&t) {...}
foo("Foo"s);
The only advantage I see using [...] instead of [...] is that in the first case the compiler can perform copy-elision (I think), which would be faster than the constructor call in the second case.
复制省略并不比构造函数调用快。无论哪种方式,您都在调用对象的构造函数之一。问题是哪个:
std::string str = "foo";
这将引发对 std::string
的构造函数的调用这需要 const char*
.但是自从std::string
必须将字符串复制到自己的存储中,它必须获取字符串的长度才能这样做。而且由于它不知道长度,这个构造函数被迫使用strlen
得到它(技术上,char_traits<char>::length
,但这可能不会更快)。
相比之下:
std::string str = "foo"s;
这将使用具有此原型(prototype)的 UDL 模板:
string operator "" s(const char* str, size_t len);
你看,编译器知道字符串文字的长度。因此,UDL 代码被传递了一个指向字符串的指针和一个大小。因此,它可以调用 std::string
采用 const char*
的构造函数和一个size_t
.所以不需要计算字符串的长度。
有问题的建议不是让您四处走动并将每次对文字的使用都转换为s
。版本。如果您对 char
数组的限制感到满意s,使用它。建议是,如果您要将文字存储在 std::string
中,最好在它仍然是字面意思而不是模糊不清时完成它const char*
.
关于c++ - 对字符串使用用户定义的文字而不是字符串文字的优点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38626341/