【问题标题】:std::string == operator not workingstd::string == 运算符不工作
【发布时间】:2010-05-11 15:47:25
【问题描述】:

多年来,我一直在 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 构建。

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

保罗

【问题讨论】:

  • 简单说明:std::string tmpStr1 = name; std::string tmpStr2 = m_dataList.get(i)->getName() ; if ( tmpStr1 == tmpStr2 ) ... 这可以正常工作。
  • getName 返回一个引用。参考仍然有效吗?
  • 无法判断给定代码有什么问题。错误在别处。 Data::getName() 的代码呢?另一个可能性是您意外覆盖了 operator==() 您是否尝试过进入它以确保您使用的是标准实现?
  • @Aprogrammer,请添加一个扩展您评论的答案。这可能是正确的答案,但如果没有例子,其他人可能看不到。
  • 我认为保罗的评论排除了简单的过时引用。比较对象的副本应该与比较对象的工作方式相同。这听起来像是某种编译器或库错误。如果是这样,我的建议是打开调试,尝试重现并单步执行库。如果没有,请戴上手套并尝试找出触发它的优化。

标签: c++ string stl


【解决方案1】:

我几乎看不出您的代码有任何问题。看来这个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”编译您的代码,并查看警告是否表明存在任何实际问题。

【讨论】:

    【解决方案2】:

    (此处暗中拍摄,因为我没有发现您的代码示例有任何问题)

    也许您的相等运算符在其他地方被重载了?除了单步执行代码以查看之外,另一种方法是显式调用您尝试从 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-03
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2017-04-14
      • 2017-06-06
      相关资源
      最近更新 更多