Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 812
zhanxw Avatar asked Dec 05 '12 14:12

zhanxw


People also ask

Can I assign a string in a const char *?

You can use the c_str() method of the string class to get a const char* with the string contents.

What is the difference between const char * and string?

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.

Can a char * be passed as const * argument?

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 ...

Should I use const char or std::string?

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.


1 Answers

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
like image 145
juanchopanza Avatar answered Oct 02 '22 15:10

juanchopanza