簡體   English   中英

std :: string ==運算符不工作

[英]std::string == operator not working

我多年來一直在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構建。

有任何想法嗎? 它對我來說看起來非常有效。

保羅

我幾乎看不到您的代碼有任何問題。 似乎這個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”編譯代碼,並查看警告是否表明存在任何實際問題。

(在黑暗中拍攝,因為我沒有看到您的代碼示例有任何問題)

也許您的平等運算符在其他地方被重載? 除了單步執行代碼之外,另一種方法是顯式調用您嘗試從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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM