0

我正在使用 rapidxml,所以我想在代码中进行这样的比较:

if ( searchNode->first_attribute("name")->value() == "foo" )

这给出了以下警告:

comparison with string literal results in unspecified behaviour [-Waddress]

将其替换为:

if ( !strcmp(searchNode->first_attribute("name")->value() , "foo") )

哪个没有警告?

后者在我看来很难看,但还有别的吗?

4

4 回答 4

4

您通常不能==用于比较 C 中的字符串,因为它只比较第一个字符的地址,这不是您想要的。

你必须使用strcmp(),但我赞成这种风格:

if( strcmp(searchNode->first_attribute("name")->value(), "foo") == 0) {  }

而不是使用!,因为该运算符是布尔运算符并且strcmp()' 的返回值不是布尔值。我意识到它有效并且定义明确,我只是认为它丑陋和混乱。

当然你可以包装它:

#include <stdbool.h>

static bool first_attrib_name_is(const Node *node, const char *string)
{
    return strcmp(node->first_attribute("name")->value(), string) == 0;
}

然后你的代码变得更可口:

if( first_attrib_name_is(searchNode, "foo") ) {  }

注意:我使用boolC99 标准的返回类型。

于 2013-05-10T11:14:56.003 回答
2

如果value()返回char*const char*,您别无选择 -strcmp或者它的长度限制替代方案之一就是您需要的。如果value()能改回来std::string,就可以回去使用了==

于 2013-05-10T11:14:11.947 回答
1

将 char* 类型与 "==" 进行比较时,您只需比较指针。如果要与“==”进行比较,请使用 C++ 字符串类型

于 2013-05-10T11:18:48.350 回答
1

你有几个选择:

您可以使用strcmp,但我建议将其包装起来。例如

bool equals(const char* a, const char* b) {
    return strcmp(a, b) == 0;
}

那么你可以写:if (equals(searchNode->first_attribute("name")->value(), "foo"))


您可以将返回值转换为 astd::string并使用==运算符

if (std::string(searchNode->first_attribute("name")->value()) == "foo")

这将引入一个字符串复制操作,根据上下文,这可能是不可取的。


您可以使用字符串引用类。字符串引用类的目的是提供一个不拥有实际字符串内容的类字符串对象。我已经看过其中的一些,并且编写自己的代码很简单,但是由于 Boost 有一个字符串引用类,我将使用它作为示例。

#include <boost/utility/string_ref.hpp>
using namespace boost;

if (string_ref(searchNode->first_attribute("name")->value()) == string_ref("foo"))
于 2013-05-10T11:29:09.703 回答