STL迁移问题(VS 2003 - > 2005)

Kon*_*rad 2 c++ migration iterator stl

我刚刚将一个项目从Visual Studio 2003转换为2005,虽然它的大部分"转换"很好,但我从以下行得到了一系列STL错误:

void SomeFn( std::vector<CSomeObject*>::iterator it,
std::vector<CSomeObject*>::iterator itBegin = NULL,
std::vector<CSomeObject*>::iterator itEnd = NULL );
Run Code Online (Sandbox Code Playgroud)

Visual Studio错误如下:

c:\<path>\Headerfile.h(20) : error C2440: 'default argument' : cannot convert from 'int' to 'std::_Vector_iterator<_Ty,_Alloc>'
        with
        [
            _Ty=CObject *,
            _Alloc=std::allocator<CObject *>
        ]
        No constructor could take the source type, or constructor overload resolution was ambiguous
Run Code Online (Sandbox Code Playgroud)

我看不出该代码有什么问题,它在VS 2003中完美运行.有什么想法吗?

Pie*_*BdR 11

您的程序不正确,因为NULL无法转换为迭代器.我真的不知道你想要将这些迭代器初始化为什么.如果您需要保证迭代器不在容器中但仍然"有效",则可以使用默认构造函数:

typedef std::vector<CSomeObject*> myvector_t;
void SomeFn( myvector_t::iterator it,
             myvector_t::iterator itBegin = myvector_t::iterator(),
             myvector_t::iterator itEnd = myvector_t::iterator() );
Run Code Online (Sandbox Code Playgroud)

但请注意,如果您这样做it,itBegin并且itEnd无法以有意义的方式进行比较!只有从给定容器中获得的迭代器才具有可比性.最后,我建议不要使用默认值itBeginitEnd.如果你真的不需要这些,那么创建一个没有参数的函数并做一些有意义的事情.即:

typedef std::vector<CSomeObject*> myvector_t;
void SomeFn( myvector_t::iterator it,
             myvector_t::iterator itBegin,
             myvector_t::iterator itEnd );
void SomeFn( myvector_t::iterator it ); // No begin/end arguments
Run Code Online (Sandbox Code Playgroud)

程序的另一个问题是使用向量来存储指针.这真的不安全.确保永远不会从矢量中删除元素而不首先删除元素.您可能还会遇到复制对象的算法问题.最好在向量中使用智能指针.