58

如果我的 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
}

是否有任何最佳实践或陷阱?

4

6 回答 6

78

有一个功能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.
}
于 2012-07-19T08:03:27.067 回答
28

没有陷阱。的默认构造std::string"". 但是您不能将字符串与NULL. 您可以获得的最接近的是使用方法检查字符串是否为空std::string::empty

于 2012-07-19T08:03:38.577 回答
22

最好的:

 std::string subCondition;

这将创建一个空字符串。

这:

std::string myStr = "";

进行复制初始化 - 从 中创建一个临时字符串"",然后使用复制构造函数来创建myStr.

奖金:

std::string myStr("");

进行直接初始化并使用string(const char*)构造函数。

要检查字符串是否为空,只需使用empty().

于 2012-07-19T08:05:53.163 回答
7

我更喜欢

if (!myStr.empty())
{
    //do something
}

你也不必写std::string a = "";。你可以写std::string a;- 默认情况下它将是空的

于 2012-07-19T08:03:14.740 回答
7

空性和“空性”是两个不同的概念。正如其他人提到的,前者可以通过 来实现std::string::empty(),后者可以通过 来实现boost::optional<std::string>,例如:

boost::optional<string> myStr;
if (myStr) { // myStr != NULL
    // ...
}
于 2015-02-05T14:36:21.840 回答
2

默认构造函数将字符串初始化为空字符串。这是说同样事情的更经济的方式。

然而,与NULL恶臭的比较。这是一种仍然普遍使用的旧语法,它意味着别的东西;一个空指针。这意味着周围没有字符串。

如果要检查字符串(确实存在)是否为空,请改用该empty方法:

if (myStr.empty()) ...
于 2012-07-19T08:06:35.923 回答