简体   繁体   English

将const char *分配给字符串是否有危险?

[英]Is there any danger of assigning a const char* to a string?

I am basically assigning a const char* value to a string. 我基本上是将const char *值分配给字符串。 I am checking for a condition and setting the string to be empty as a default value. 我正在检查条件,并将字符串设置为空作为默认值。

In the parameterised constructor I am setting the string to be empty as follows 在参数化的构造函数中,我将字符串设置为空,如下所示

ClassName:: ClassName(X x, string name):X(x), name(){}

I set the string empty once I am done using it as 使用完后,将字符串设置为空

name="";

Is the above approach of initialisation correct? 以上初始化方法正确吗?

Also is there any risk of assigning a const char* to a string? 还有为字符串分配const char *的风险吗?

const char* diag;
string name;

name= diag;

The class std::string has corresponding constructors and assignment operators for objects of type char * . std::string类具有用于char *类型的对象的对应构造函数和赋值运算符。 The only problem that can arise relative to the objects of this type is when the initializer is a null pointer. 相对于这种类型的对象可能出现的唯一问题是初始化程序为空指针时。

Take into account that if there is declared a variable like this 考虑到是否声明了这样的变量

const char *name = "";

then name is not a null pointer. 那么name不是空指针。 It is a pointer to the first character (character '\\0' ) of an array of type const char[1] that corresponds to the "empty" string literal and that has the static storage duration. 它是指向类型为const char[1]的数组的第一个字符(字符'\\0' )的指针,该数组对应于“空”字符串文字并具有静态存储持续时间。

If you write for example 如果你写例如

std::strig s( name );

or 要么

std::string s = name;

then you will get an empty object s of type std::string becsuse there is nothing to copy from the "empty" string literal. 那么你会得到一个空对象s类型std::string becsuse没有什么可以从“空”的字符串文字复制。

Thus it does not make sense to declare objects of type std::string such a way. 因此,以这种方式声明类型为std::string对象是没有意义的。 It is enough to write 写就足够了

std::string s;

在您的示例中没有问题,但是通常您需要知道const char *指向的字符数组以空const char *结尾,否则std :: string构造函数将继续读取内存,直到结束为止。数组。

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

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