Why can I use const char * as a key in std :: map <std :: string, int>

I defined a data structure

std::map<std::string, int> a; 

I found that I can pass const char * as a key, for example:

 a["abc"] = 1; 

Which function provides automatic type conversion from const char * to std :: string?

+7
source share
4 answers

std::string has a constructor that allows for implicit conversion from const char* .

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

means implicit conversion like

 std::string s = "Hello"; 

allowed.

This is the equivalent of doing something like

 struct Foo { Foo() {} Foo(int) {} // implicit converting constructor. }; Foo f1 = 42; Foo f2; f2 = 33 + 9; 

If you want to prohibit the construction of an implicit conversion, you mark the constructor as explicit :

 struct Foo { explicit Foo(int) {} }; Foo f = 33+9; // error Foo f(33+9); // OK f = Foo(33+9); // OK 
+15
source

There is a constructor for std :: string that takes a const char * parameter as a parameter.

 string::string(const char*); 

If the constructor is not declared explicit, then the compiler will use one use of the converted transformation, if necessary, to call any function.

+4
source

See row constructor . The constructor provides a key conversion on your card. It is equivalent

 a[std::string("abc")] = 1; 
+3
source

In C ++, if you create a constructor for a class that takes only one parameter, then (unless you specify otherwise with explicit ), this type of parameter will be implicitly converted to your class.

std::string has such a constructor for char *

Yes, this can lead to unexpected behavior. That's why you should usually put explicit in one-parameter constructors if you really don't want these silent conversions.

+2
source

All Articles