花括号初始化与std::string

huangapple go评论64阅读模式
英文:

Curly Brace Initialisation with std::string

问题

我最近越来越多地使用花括号初始化。尽管我在这种情况下发现与圆括号初始化有所不同,我想知道为什么。

如果我这样做:
```c++
const std::string s(5, '=');
std::cout << s << std::endl;

我会得到:

=====

这是我预期的结果。但是如果我这样做:

const std::string s{5, '='};
std::cout << s << std::endl;

我会得到:

=

为什么会这样?


编辑:为了让看到这个的任何人受益,第二个输出中的 `=` 前面有一个不可打印的字符。它在stackoverflow上不显示。看起来像这样:

花括号初始化与std::string

英文:

I have been using curly brace initialisation more and more recently. Although I found a difference to round bracket initialisation in this case and I was wondering why.

If I do:

const std::string s(5, &#39;=&#39;);
std::cout &lt;&lt; s &lt;&lt; std::endl;

I get:

=====

This is what I expect. But if I do:

const std::string s{5, &#39;=&#39;};
std::cout &lt;&lt; s &lt;&lt; std::endl;

I get:

=

Why is this?

Edit: For the benefit for anyone that sees this. There is an unprintable character before the = in the second output. It just doesn't show on stackoverflow. Looks like:

花括号初始化与std::string

答案1

得分: 5

这部分内容的翻译如下:

const std::string s(5, '=');

使用了接受_count_和字符_ch_(以及分配器)的构造函数:

constexpr basic_string(size_type count, CharT ch,
                        const Allocator& alloc = Allocator());

但是

const std::string s{5, '='};

使用了

constexpr basic_string(std::initializer_list<CharT> ilist,
                        const Allocator& alloc = Allocator());

这意味着5将被转换为一个char,因此你的字符串的大小将是2。第一个字符将具有值5,而另一个字符将是=

英文:

This

const std::string s(5, &#39;=&#39;);

uses the constructor taking a count and the character, ch (as well as an allocator):

constexpr basic_string( size_type count, CharT ch,
                        const Allocator&amp; alloc = Allocator() );

But

const std::string s{5, &#39;=&#39;};

uses

constexpr basic_string( std::initializer_list&lt;CharT&gt; ilist,
                        const Allocator&amp; alloc = Allocator() );

which means that 5 will be converted to a char and your string will therefore have the size 2. The first character will have the value 5 and the other will be =.

huangapple
  • 本文由 发表于 2023年6月8日 03:24:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76426517.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定