gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 16:07:18 25 4
gpt4 key购买 nike

我可以看到 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-listconstructors (8.5.4) of the class T and the argument list consists ofthe initializer list as a single argument.

— If no viableinitializer-list constructor is found, overload resolution isperformed again, where the candidate functions are all theconstructors of the class T and the argument list consists of theelements 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com