我应该检查"std::string.c_str"是否为空吗?

Should I check if "std::string.c_str" is NULL?

本文关键字:是否 str 检查 std string 我应该      更新时间:2023-10-16

我正在用Xcode编写代码C++代码。在实例中,我确保所有字段都有效。

SomeClass *myclass = new SomeClass();
std::string myString;
if ( (myClass) && (myString.c_str)) {
return true;
} else {
return false;
}

我应该检查testString.c_str吗?有意义吗?

new(( 运算符的默认行为是返回新对象,或者在内存分配失败时引发异常。因此,您无需检查myClass是否为 NULL,除非您设置标志来更改行为或为您的类实现您自己的 new(( 运算符。

此外,myClass周围的额外括号是不必要的。表达您要检查的内容的更好方法是

if ((myClass != nullptr) && 

然后,您当前正在测试std::string类中c_str()的方法的地址是否不为 NULL。我猜不想你想做。
首先,您需要编写myString.c_str()。然后,此方法永远不会返回 NULL 指针,它可以返回的是一个空的 C 字符串。但这最好用std::string::empty()进行测试,所以你的支票看起来像这样:

if (myString.empty()) {
return false;
} else {
return true;
}

当然可以缩短为

return !myString.empty();

最后:如果你在函数/方法中有这段代码:谁删除了你的新 SomeClass 对象?