c++ - 为什么 std::string {"const char ptr"} 有效?

标签 c++ c++11 stdstring initialization-list uniform-initialization

我可以看到 std::string 只有一个 CTOR 为 initializer_list : string (initializer_list<char> il);所以初始化列表应该使用字符,对吧?为什么 std::string{"some_str"}有效,它得到 const char* ,对吧?

最佳答案

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 有很多 constructors .其中之一,接收 const char*

因此,首先编译器将在重载解析中采用 initializer_list c-tor,但当 stringconst char*< 构造时,它不是可行的候选者,然后编译器会查看其他构造函数并选择最好的一个,即

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

你可以用简单的例子来检查它:

#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

关于c++ - 为什么 std::string {"const char ptr"} 有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33298375/

相关文章:

c++ - CPP 字符串构造函数查找并追加空字符

c++ - basic_string<CharT> 与 CharT*

java - Android NDK UnsatisfiedLinkError 未找到 native 方法

c++ - Gtkmm 程序编译正常但崩溃 - Windows XP

c++ - 为什么我不能为构造函数(C++)指定调用约定?

C++ 不允许指向不完整类类型的指针

c++ - Libcurl 停止工作,SSL 连接错误

c++ - 结构 vector push_back C++

c++ - Listen 套接字仅在 g++ 中工作,没有 -std=c++11

c++ - 了解在共享库中重载 operator new 的行为