av4*_*625 4 c++ stdstring curly-braces
我最近越来越多地使用大括号初始化。尽管我发现在这种情况下圆括号初始化存在差异,但我想知道为什么。
如果我做:
const std::string s(5, '=');
std::cout << s << std::endl;
Run Code Online (Sandbox Code Playgroud)
我得到:
=====
Run Code Online (Sandbox Code Playgroud)
这就是我所期望的。但如果我这样做:
=====
Run Code Online (Sandbox Code Playgroud)
我得到:
=
Run Code Online (Sandbox Code Playgroud)
为什么是这样?
编辑:为了任何看到此内容的人的利益。=第二个输出中的之前有一个不可打印的字符。它只是没有显示在 stackoverflow 上。好像:
这
const std::string s(5, '=');
Run Code Online (Sandbox Code Playgroud)
使用带有计数和字符ch的构造函数(以及分配器):
constexpr basic_string( size_type count, CharT ch,
const Allocator& alloc = Allocator() );
Run Code Online (Sandbox Code Playgroud)
但
const std::string s{5, '='};
Run Code Online (Sandbox Code Playgroud)
用途
constexpr basic_string( std::initializer_list<CharT> ilist,
const Allocator& alloc = Allocator() );
Run Code Online (Sandbox Code Playgroud)
这意味着它将5被转换为 achar并且您的字符串因此将具有大小2。第一个字符的值为5,另一个字符的值为=。