简体   繁体   English

我们可以将 const char* 分配给 cpp 中的字符串吗?

[英]Can we assign const char* to a string in cpp?

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虽然我的编译器在将 const char* 分配给字符串时没有抛出错误,但我想知道这个分配是否真的有效并且不会抛出一些意外的结果

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. std::string旨在替换乏味且容易出错的 C 字符串const char*因此要使其成为一个很好的替换/后继者,它需要与const char*向后兼容。

name = name2; calls operator= so if we check basic_string s overloads for this operator we can see (3):调用operator=所以如果我们检查这个运算符的basic_string s重载, 我们可以看到(3):

basic_string& operator=( const CharT* s );

Here CharT is of the type char so you get const char*这里CharTchar类型,所以你得到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 :它会做您期望它做的事情,它将const char*指向的内容复制到std::string的内部缓冲区:

Replaces the contents with those of null-terminated character string pointed to by s as if by assign(s, Traits::length(s)) .将内容替换为s指向的以空字符结尾的字符串的内容,就像通过assign(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.但是,为了走另一条路线,从std::stringconst char* ,您需要在std::string对象上调用其方法c_str()

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).注意name = name2调用 std::string 赋值运算符,之后这两个变量是完全独立的,即您可以自由更改name ,而name2保持 const (又名文字字符串)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM