Reputation: 3279
I have define a data structure
std::map<std::string, int> a;
I found I can pass const char* as key, like this:
a["abc"] = 1;
Which function provides automatic type conversion from const char* to std::string?
Upvotes: 7
Views: 2233
Reputation: 227390
std::string
has a constructor that allows the implicit conversion from const char*
.
basic_string( const CharT* s,
const Allocator& alloc = Allocator() );
means that an implicit conversion such as
std::string s = "Hello";
is allowed.
It 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 wanted to disallow the implicit conversion construction, 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
Upvotes: 16
Reputation: 44804
In C++ if you make a class constructor that only takes one parameter, then (unless you tell it otherwise with explicit
), that parameter's type will be implicitly convertable to your class.
std::string
has such a constructor for char *
Yes, this can cause some unexpected behavior on occasion. This is why you generally should put explicit
on single-parameter constructors, unless you really want these silent conversions.
Upvotes: 2
Reputation: 74018
See string constructor. The constructor provides the conversion for the key in your map. It's equivalent to
a[std::string("abc")] = 1;
Upvotes: 3
Reputation: 30035
There is a constructor for std::string which takes const char* as a parameter.
string::string(const char*);
Unless the constructor is declared explicit then the compiler will apply one use defined conversion if needed to call any function.
Upvotes: 4