0

I haven't worked with C++ for several years and now I'm required to maintain a C++ project. I have the following piece of code which seems to compile in one project, but not in the other.

list.h

#include "mytype.h"
#include <set>

typedef std::set<MYTYPE> MYTYPE_LIST;
typedef MYTYPE_LIST::iterator MYTYPE_LIST_ITERATOR;

class LIST {

[...]

MYTYPE_LIST list;
};

list.cpp

void 
LIST::somemethod(MYTYPE* requester)
{

   MYTYPE_LIST_ITERATOR it;
   for (it = list.begin(); it != list.end() ; it++ )
   {
      MYTYPE& info = (*it); // Error on this line
      [...]
   }
}

I am compiling my project with VS 2010, and I get the following errors on the marked line:

error C2440: 'initializing' : cannot convert from 'const MYTYPE' to 'MYTYPE &'
IntelliSense: qualifiers dropped in binding reference of type "MYTYPE &" to initializer of type "const MYTYPE"

I googled these errors, and as far as I understand, (*it) should not be const (because 'it' is not a ::const_iterator, see here), and therefor, I should be able to assign it to the reference variable.

Community
  • 1
  • 1
Hila
  • 1,080
  • 1
  • 9
  • 22

2 Answers2

1

In a std::set the data is the key, and since keys are constant you can't get a non-const reference.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Eventually I found that in VS 2010, Microsoft introduced a change which breaks backward compatibility with this code.

Apparently, this change was made for good reasons - modifying a set element might break the set's invariants. See here, "Problem 3: error C2662: 'NamedNumber::change_name' : cannot convert 'this' pointer from 'const NamedNumber' to 'NamedNumber &'".

The other project was compiled with and old version of Visual Studio, so we had no problem there.

Hila
  • 1,080
  • 1
  • 9
  • 22