C++ - 使用std :: string的统一初始化程序

Hil*_*man 9 c++ string uniform-initialization c++11 list-initialization

我正在尝试使用C++字符串类的统一初始化程序.以下是代码:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str1 {"aaaaa"};
    string str2 {5, 'a'};
    string str3 (5, 'a');

    cout << "str1: " << str1 << endl;
    cout << "str2: " << str2 << endl;
    cout << "str3: " << str3 << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出将是:

str1: aaaaa
str2: a
str3: aaaaa
Run Code Online (Sandbox Code Playgroud)

这让我摸不着头脑.为什么str2不能达到预期的效果str3呢?

Whi*_*TiM 9

你正在使用这个siganture std::string的构造函数

std::basic_string( std::initializer_list<CharT> init, const Allocator& alloc = Allocator() );
Run Code Online (Sandbox Code Playgroud)

并将编译器视为5一种char类型,转换ASCII为未在屏幕上打印的类型.如果将其更改5为可打印值,例如,A其ASCII值是65,

string str2 {65, 'a'};
Run Code Online (Sandbox Code Playgroud)

它将打印:

Aa
Run Code Online (Sandbox Code Playgroud)

在附近的插图中看到Live on Coliru


Pra*_*ian 5

std::string has a constructor that takes an initializer_list argument.

basic_string( std::initializer_list<CharT> init,
              const Allocator& alloc = Allocator() );
Run Code Online (Sandbox Code Playgroud)

That constructor always gets precedence when you use a braced-init-list to construct std::string. The other constructors are only considered if the elements in the braced-init-list are not convertible to the type of elements in the initializer_list. This is mentioned in [over.match.list]/1.

Initially, the candidate functions are the initializer-list constructors ([dcl.init.list]) of the class T and the argument list consists of the initializer list as a single argument.

In your example, the first argument 5 is implicitly convertible to char, so the initializer_list constructor is viable, and it gets chosen.

This is evident if you print each character in the strings as ints

void print(char const *prefix, string& s)
{
    cout << prefix << s << ", size " << s.size() << ": ";
    for(int c : s) cout << c << ' ';
    cout << '\n';
}

string str1 {"aaaaa"};
string str2 {5, 'a'};
string str3 (5, 'a');

print("str1: ", str1);
print("str2: ", str2);
print("str3: ", str3);
Run Code Online (Sandbox Code Playgroud)

Output:

str1: aaaaa, size 5: 97 97 97 97 97 
str2: a, size 2: 5 97 
str3: aaaaa, size 5: 97 97 97 97 97 
Run Code Online (Sandbox Code Playgroud)

Live demo