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?
You can use the c_str() method of the string class to get a const char* with the string contents.
string is an object meant to hold textual data (a string), and char* is a pointer to a block of memory that is meant to hold textual data (a string). A string "knows" its length, but a char* is just a pointer (to an array of characters) -- it has no length information.
In general, you can pass a char * into something that expects a const char * without an explicit cast because that's a safe thing to do (give something modifiable to something that doesn't intend to modify it), but you can't pass a const char * into something expecting a char * (without an explicit cast) because that's ...
For string literals, and only for string constants that come from literals, I would use const char[] . The main advantage of std::string is that it has memory management for free, but that is not an issue with string literals.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With