C++ find方法不是const吗?
我编写了一个方法,我想将其声明为 const,但编译器会抱怨。我追踪并发现方法的这一部分造成了困难:
bool ClassA::MethodA(int x)
{
bool y = false;
if(find(myList.begin(), myList.end(), x) != myList.end())
{
y = true;
}
return y;
}
该方法中发生的事情比这更多,但剥离掉其他所有内容后,这就是不允许该方法成为 const 的部分。为什么stl find算法会阻止方法成为const?它会以任何方式改变列表吗?
I've written a method that I'd like to declare as const, but the compiler complains. I traced through and found that this part of the method was causing the difficulty:
bool ClassA::MethodA(int x)
{
bool y = false;
if(find(myList.begin(), myList.end(), x) != myList.end())
{
y = true;
}
return y;
}
There is more happening in the method than that, but with everything else stripped away, this was the part that didn't allow the method to be const. Why does the stl find algorithm prevent the method from being const? Does it change the list in any way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果 myList 是自定义容器类型的对象,并且其 begin() 和 end() 方法没有 const 重载,则可能会出现问题。另外,假设 x 的类型在您的代码中可能不是真正的 int ,您确定有一个相等运算符可以对该类型的 const 成员进行操作吗?
If myList is an object of a custom container type, you could have a problem if its begin() and end() methods don't have a const overload. Also, assuming perhaps the type of x isn't really int in your code, are you sure there's an equality operator that can operate on a const member of that type?
我复制了您的实现,没有任何问题:
当您尝试将方法定义(上面发布的内容)设置为 const 时,您是否还记得更改方法声明?
I copied your implementation and had no problems with it:
When you tried to make the method definition (what you posted above) const, did you remember to change the method declaration as well?
对我来说效果很好(i686-apple-darwin10-g++-4.2.1 (GCC) 4.2.1(Apple Inc. build 5646)):
Works fine for me (i686-apple-darwin10-g++-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5646)):
贴出完整的程序,但编译失败。这编译得很好:
也许
find
没有调用您认为它是的函数[编辑:更可能的是,愚蠢的我,myList 不是std::list
]。缩减为一个演示问题的小程序可能会揭示原因,因为在某些时候你会删除一些东西,它就会开始工作。Post a complete program which fails to compile. This compiles fine:
Maybe
find
isn't calling the function you think it is [Edit: more likely, silly me, myList isn't astd::list
]. Cutting down to a small program which demonstrates the problem will probably reveal the cause, because at some point you'll remove something and it will start working.