为什么我可以在std :: map <std :: string,int>中使用const char*作为键

zha*_*nxw 7 c++ type-conversion

我已经定义了一个数据结构

std::map<std::string, int> a;
Run Code Online (Sandbox Code Playgroud)

我发现我可以传递const char*作为键,如下所示:

a["abc"] = 1;
Run Code Online (Sandbox Code Playgroud)

哪个函数提供从const char*到std :: string的自动类型转换?

jua*_*nza 16

std::string有一个允许隐式转换const char*构造函数.

basic_string( const CharT* s,
              const Allocator& alloc = Allocator() );
Run Code Online (Sandbox Code Playgroud)

意味着隐式转换,如

std::string s = "Hello";
Run Code Online (Sandbox Code Playgroud)

被允许.

这相当于做了类似的事情

struct Foo
{
  Foo() {}
  Foo(int) {} // implicit converting constructor.
};

Foo f1 = 42;
Foo f2;
f2 = 33 + 9;
Run Code Online (Sandbox Code Playgroud)

如果要禁止隐式转换构造,请将构造函数标记为explicit:

struct Foo 
{
  explicit Foo(int) {}
};

Foo f = 33+9; // error
Foo f(33+9); // OK
f = Foo(33+9); // OK
Run Code Online (Sandbox Code Playgroud)