views:

238

answers:

4

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?

A: 

Works fine for me (i686-apple-darwin10-g++-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5646)):

#include <list>
#include <algorithm>

class ClassA
{
public:
  ClassA() { myList.push_back(1); myList.push_back(2); }
  bool MethodA(int x) const;
private:
  std::list<int> myList;
};

bool ClassA::MethodA(int x) const
{
  bool y = false;
  if(find(myList.begin(), myList.end(), x) != myList.end())
    {
      y = true;
    }
  return y;
}

int main( int argc, char** argv )
{
  ClassA a;
  a.MethodA(5);
  return 0;
}
Jesse
A: 

Post a complete program which fails to compile. This compiles fine:

#include <list>
#include <algorithm>
#include <iostream>

struct Foo {
    std::list<int> ml;
    bool search(int x) const {
        return std::find(ml.begin(), ml.end(), x) != ml.end();
    }
};

int main() {
    const Foo f;
    std::cout << f.search(0) << "\n";
}

Maybe find isn't calling the function you think it is [Edit: more likely, silly me, myList isn't a std::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.

Steve Jessop
+2  A: 

I copied your implementation and had no problems with it:

class ClassA
{
    vector<int> myList;
public:
    bool MethodA(int x) const;
};

bool ClassA::MethodA(int x) const
{
    bool y = false;
    if (find(myList.begin(), myList.end(), x) != myList.end())
        y = true;

    return y;
}

When you tried to make the method definition (what you posted above) const, did you remember to change the method declaration as well?

Dathan
+5  A: 

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?

Mike Dinsdale
Nice detective work. Of course, the answer would have been obvious if @Rachel had just posted the compiler error.
rlbond