Although my compiler doesn't throw an error while assigning const char* to a string, I am wondering if this assignment is really valid and will not throw some unexpected result
string name;
const char* name2 = "ABCD";
name = name2;
You absolutely can.
std::string
was meant to replace the tedious and error-prone C strings const char*
so for it to be a good replacement/successor it'd need backwards compatibility with const char*
which it does.
name = name2;
calls operator=
so if we check basic_string
s overloads for this operator we can see (3):
basic_string& operator=( const CharT* s );
Here CharT
is of the type char
so you get const char*
Which does what you'd expect it to do, it copies over the contents the const char*
is pointing to, to the internal buffer of std::string
:
Replaces the contents with those of null-terminated character string pointed to by
s
as if byassign(s, Traits::length(s))
.
In order to go the other route though, from a std::string
to a const char*
, you'd need to call its method c_str()
on the std::string
object.
I am wondering if this assignment is really valid
Yes it's valid:
string name;
const char *name2 = "ABCD";
name = name2;
Note name = name2
calls std::string assignment operator, after which the two variables are totally independent, ie you are free to change name
, while name2
remains const (aka literal string).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.