Std :: string == statement does not work

I have been using the std :: string == operator for many years on windows and linux. Now I am compiling one of my libraries on linux, it uses == heavily. In linux, the following function fails because == returns false even if the lines are equal (case sensitive)

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 creating gcc 4.4.1 and libstdc ++ 44-4.4.1.

Any ideas? It looks absolutely fair to me.

Floor

+4
source share
2 answers

I hardly see problems with your code. The origin of the error seems to be in a different place.

I assume that you will return the local variable reference.

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, in some environments I experienced an exception. This code is not valid, but the behavior is undefined. Apparently, it often works correctly.

Watch for compilation warnings, for example:

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

You can also try compiling your code with the -Wall option and see if any real problems are being warned.

+2
source

(A shot in the dark here, since I see nothing wrong with your code example)

Perhaps your equality operator is overloaded elsewhere? Besides the fact that you are looking at the code to see, another way is to explicitly call the equality operator you are trying to achieve from std ::. For instance:

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

Must output:

 Matches Matches 2 
+1
source

Source: https://habr.com/ru/post/1309439/


All Articles