std::string == 运算符不起作用
我多年来一直在 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.
有什么想法吗?这对我来说看起来完全有效。
保罗
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我几乎看不出你的代码有什么问题。看来该错误的根源在其他地方。
我猜你返回了局部变量的引用。
请参阅我的示例:
我的机器上的输出:
但是,我在某些环境中遇到了异常输出。这是无效代码,但未定义行为。显然,它通常工作正常。
请注意编译警告,例如:
您还可以尝试使用选项“-Wall”编译代码,并查看警告是否表明存在任何实际问题。
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:
Output on my machine:
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:
You may also try to compile your code with option "-Wall" and see whether warning indicate any real problems.
(这里是在黑暗中拍摄的,因为我没有看到你的代码示例有任何问题)
也许你的等式运算符在其他地方被重载了?除了逐步查看代码之外,另一种方法是显式调用您试图从 std:: 访问的相等运算符。例如:
应该输出:
(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:
Should output: