简体   繁体   English

为什么std :: string {“ const char ptr”}有效?

[英]Why std::string{“const char ptr”} works?

I can see that std::string has only one CTOR with initializer_list : string (initializer_list<char> il); 我可以看到std :: string仅具有一个带有initializer_list CTOR: string (initializer_list<char> il); So initializer list should work with chars, right? 因此,初始化列表应与char一起使用,对吗? Why std::string{"some_str"} works, it gets const char* , right? 为什么std::string{"some_str"}起作用,它得到const char* ,对吗?

n3337 13.3.1.7/1 n3337 13.3.1.7/1

When objects of non-aggregate class type T are list-initialized (8.5.4), overload resolution selects the constructor in two phases: 当非聚合类类型T的对象被列表初始化(8.5.4)时,重载解析会分两个阶段选择构造函数:

— Initially, the candidate functions are the initializer-list constructors (8.5.4) of the class T and the argument list consists of the initializer list as a single argument. —最初,候选函数是类T的初始化器列表构造函数(8.5.4),参数列表由作为单个参数的初始化器列表组成。

— If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all the constructors of the class T and the argument list consists of the elements of the initializer list. —如果找不到可行的initializer-list构造函数,则再次执行重载解析,其中候选函数是T类的所有构造函数,而参数列表由Initializer列表的元素组成。

std::string has many constructors . std::string有很多构造函数 One of them, that receives const char* . 其中之一,接收const char*

So, firstly compiler will take initializer_list c-tor in overload-resolution, but it's not viable candidate, when string is constructed with const char* , then compiler will look at other constructors and choose the best one, that is 因此,首先编译器将采用重载分辨率的initializer_list c-tor,但它不是可行的候选者,当使用const char*构造string时,编译器将查看其他构造函数并选择最佳构造函数,即

basic_string( const CharT* s,
              const Allocator& alloc = Allocator() );

You can check it with just simple example: 您可以通过简单的示例进行检查:

#include <initializer_list>
#include <iostream>

class String
{
public:
   String(const std::initializer_list<char>&) { std::cout << "init-list c-tor called" << std::endl; }
   String(const char*) { std::cout << "const char* c-tor called" << std::endl; }
};

int main()
{
   String s{"hello"};
}

Live version 现场版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM