Benjamin Cuningham
Benjamin Cuningham

Reputation: 906

Why does const_cast<iterator>(const_iterator) work in Visual C++ 6.0, but not in Visual Studio .NET?

I am trying to modernize some old C++ code. It was originally built in Visual C++ 6.0. My current approach is to Step through the versions of Visual Studio one at a time to minimize how much of the code breaks per iteration.

Take the following example:

vector<someType>::iterator someFunction(...){
    vector<someType>::const_iterator someConstIterator;
    ...
    return (const_cast<vector<someType>::iterator>(someConstIterator));
}

In Visual C++ 6.0, it compiles just fine. In Visual Studio .NET, I get the following error:

error C2440: 'const_cast': cannot convert from 'vector::const_iterator' to 'vector::iterator'

What has changed? Is it a library change? A C++ version change?

Upvotes: 2

Views: 331

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726909

Since const_cast<T> is allowed under four specific circumstances listed here, you cannot generally convert

vector<T>::const_iterator

to

vector<T>::iterator

unless the source and target types are pointers or types that differ only in cv-qualification.

Since vector<T>::const_iterator could not be defined as const vector<T>::iterator because vector<T>::const_iterator needs to remain changeable, the only reasonable explanation is that both vector<T>::const_iterator and vector<T>::iterator were typedef-ed as pointers in the Visual C++ 6.0 library, but the library that ships with Visual Studio .NET has changed.

Upvotes: 3

Related Questions