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

标签 c++ stl migration iterator

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

void SomeFn( std::vector<CSomeObject*>::iterator it,
std::vector<CSomeObject*>::iterator itBegin = NULL,
std::vector<CSomeObject*>::iterator itEnd = NULL );

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

我看不出该代码有任何问题,它在 VS 2003 中运行良好。有什么想法吗?

最佳答案

您的程序不正确,因为 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() );

但是请注意,如果您这样做,ititBeginitEnd 将无法进行有意义的比较!只有从给定容器中获得的迭代器才具有可比性。最后,我建议不要对 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

您的程序的另一个问题是使用 vector 来存储指针。这真的很不安全。确保在不先删除元素的情况下永远不要从 vector 中删除元素。您可能还会遇到算法复制对象的问题。最好在 vector 中使用智能指针。

关于c++ - STL 迁移问题(VS 2003 -> 2005),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/283646/

相关文章:

c++ - 非常简单的c++程序中的lnk2019错误

c++ - 测量执行简单指令的时间

c# - 在 C++ 中将 std::string 用于非托管 C# dll

ruby-on-rails - 将更新逻辑放入您的迁移中

c++ - 如何使用 Solaris Studio 12.4 编译器构建 Boost V1.57

c++ - 使用 ninja 和 clang++ 时 vim 中的 Quickfix 列表

php - PHP 产品从 PHP 5.2 迁移到 PHP 5.4 的工具或方法

mysql - 如何将数据库从 Postgres 迁移到 MySQL?

c++ - STL 容器的 Const 锁包装器

c++ - 对 STL 容器的安全并行只读访问