简体   繁体   中英

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); So initializer list should work with chars, right? Why std::string{"some_str"} works, it gets const char* , right?

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:

— 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.

— 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.

std::string has many constructors . One of them, that receives 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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