std::string == 运算符不起作用

4

我多年来一直在Windows和Linux上使用std::string的==运算符。现在我正在Linux上编译我的一个库,它大量使用了==。在Linux上,以下函数失败,因为==返回false,即使字符串相等(区分大小写)。

const Data* DataBase::getDataByName( const std::string& name ) const
{
         for ( unsigned int i = 0 ; i < m_dataList.getNum() ; i++ )
         {
                if (  m_dataList.get(i)->getName() == name )
                {
                         return  m_dataList.get(i);
                }
         }

         return NULL;
}

getName()方法声明如下:

virtual const std::string& getName() const;

我正在使用gcc 4.4.1和libstdc++44-4.4.1进行构建。

有什么想法吗?在我看来,它看起来完全有效。

保罗


1
只是一个快速的提示:std::string tmpStr1 = name; std::string tmpStr2 = m_dataList.get(i)->getName() ;如果 ( tmpStr1 == tmpStr2 ) ...这个按预期工作得很好。 - Paul
9
getName返回一个引用,那么这个引用是否仍然有效? - AProgrammer
2
很难确定给定代码的问题所在。错误可能出现在其他地方。Data::getName() 的代码怎么样?另一个可能性是您意外覆盖了 operator==(),您尝试进入它以确保您正在使用标准实现了吗? - Martin York
@Aprogrammer,请添加一个回答,详细说明您的评论。这可能是正确的答案,但其他人可能没有看到它,如果没有示例的话。 - deft_code
这个问题是“总是”失败还是间歇性地失败?它是否在您的虚拟getName()方法定义的特定子类类型中失败? - Armentage
显示剩余2条评论
2个回答

2

我觉得你的代码没有什么问题。看起来bug的根源在其他地方。

我猜你返回了一个局部变量的引用。

看看我的例子:

#include <iostream>

using std::string;

const string& getString()
{
    string text("abc");
    return text;
}

int main() {
    string text("abc");
    std::cout << (getString() == text ? "True" : "False") << "\n";
    return 0;
};

我的电脑上的输出:

False

然而,在某些环境中,我遇到了期望的输出。虽然它是无效的代码,但行为并未定义。显然,通常情况下它能正常工作。

注意编译警告,例如:

a.cpp:7: warning: reference to local variable ‘text’ returned

您可以尝试使用选项“-Wall”编译您的代码,并查看警告是否指示任何实际问题。

1

这里可能是猜测,因为我没有看到你的代码样本有任何问题。

也许你的等号运算符在其他地方被重载了?除了逐步执行代码以查看之外,另一种方法是从std::中显式调用你要访问的等号运算符。例如:

#include <iostream>

int main(void)
{
    const std::string lhs = "hello";
    const std::string rhs = "hello";

    if (lhs == rhs)
    {
        std::cout << "Matches" << std::endl;
    }

    if (std::operator==( lhs, rhs ) == true)
    {
        std::cout << "Matches 2" << std::endl;
    }

    return 0;
}

应输出:
Matches
Matches 2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接