tags:

views:

183

answers:

2

Hello,

I've been using std::string's == operator for years on windows and linux. Now I am compiling one of my libraries on linux, it uses == heavily. On linux the following function fails, because the == returns false even when the strings are equal (case sensitive wise equal)

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;
}

The getName() method is declared as follows

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

I am building with gcc 4.4.1 and libstdc++44-4.4.1.

Any ideas? it looks perfectly valid to me.

Paul

A: 

(Shot in the dark here as I don't see anything wrong with your code sample)

Perhaps your equality operator is being overloaded elsewhere? Aside from stepping through the code to see, one other way is to explicitly call the equality operator you're trying to reach from std::. For example:

#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;
}

Should output:

Matches
Matches 2
reshen
+1  A: 

I could hardly see any problem with your code. It seems that the origin of the bug is elsewhere.

I guess that you return the reference of a local variable.

See my example:

#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;
};

Output on my machine:

False

However I experienced in some environments the excepted output. It is an invalid code, but the behavior is not defined. Apparently, often it works correctly.

Watch out for the compilation warnings like:

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

You may also try to compile your code with option "-Wall" and see whether warning indicate any real problems.

Jakozaur