如果我的 C++ 代码(如下所示)有一个初始化为空字符串的字符串,这会重要吗:
std::string myStr = "";
....some code to optionally populate 'myStr'...
if (myStr != "") {
// do something
}
对比无/空初始化:
std::string myStr;
....some code to optionally populate 'myStr'...
if (myStr != NULL) {
// do something
}
这里有什么问题吗?
empty()
有一个功能
std::string:
已经为你准备好了
std::string a;
if(a.empty())
{
//do stuff. You will enter this block if the string is declared like this
}
或
std::string a;
if(!a.empty())
{
//You will not enter this block now
}
a = "42";
if(!a.empty())
{
//And now you will enter this block.
}
没有任何陷阱。
std::string
的默认结构是 ""
。但你不能将字符串与 NULL
进行比较。最接近的是使用 std::string::empty
方法检查字符串是否为空..
最佳:
std::string subCondition;
这会创建一个空字符串。
这个:
std::string myStr = "";
进行复制初始化 - 从
""
创建临时字符串,然后使用复制构造函数创建 myStr
。
奖金:
std::string myStr("");
直接初始化并使用
string(const char*)
构造函数。
要检查字符串是否为空,只需使用
empty()
。
我更喜欢
if (!myStr.empty())
{
//do something
}
而且你不必写
std::string a = "";
。你可以只写std::string a;
- 默认情况下它是空的
空和“NULL”是两个不同的概念。正如其他人提到的,前者可以通过
std::string::empty()
实现,后者可以通过 boost::optional<std::string>
实现,例如:
boost::optional<string> myStr;
if (myStr) { // myStr != NULL
// ...
}
默认构造函数将字符串初始化为空字符串。这是表达同一件事的更经济的方式。
然而,与
NULL
的比较很糟糕。这是一种仍在普遍使用的旧语法,它的含义是不同的。一个空指针。这意味着周围没有绳子。
如果要检查字符串(确实存在)是否为空,请使用
empty
方法:
if (myStr.empty()) ...