我有以下一段粗心的 C++ 代码,它在 VC10 下编译顺利,但在运行时却惨遭失败。我想知道是否有一种方法可以在编译时验证这种错误?
#include "stdafx.h"
#include <set>
void minus(std::set<int>& lhs, const std::set<int>& rhs)
{
for ( auto i = rhs.cbegin(); i != rhs.cend(); ++i )
{
lhs.erase(i); // !!! while I meant "*i" !!!
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int v_lhs[] = {0,1,2,3,4,5};
std::set<int> s_lhs(&v_lhs[0], &v_lhs[sizeof(v_lhs) / sizeof(int)]);
int v_rhs[] = {1,3,5};
std::set<int> s_rhs(&v_rhs[0], &v_rhs[sizeof(v_rhs) / sizeof(int)]);
minus(s_lhs, s_rhs);
return 0;
}
请注意,我完全知道 C++11(VC10 早期部分采用)已经纠正了“erase”实际上采用“const_iterator”的行为。
在此先感谢您提供任何宝贵的意见。
最佳答案
C++ 不是一种读心术的语言。它只知道类型。它知道 erase
采用迭代器。它知道 i
是一个相同类型的迭代器。因此,就C++的编译器规则而言,调用erase(i)
是合法的。
编译器无法知道您想做什么。编译器也没有办法知道i
的内容 不适合erase
的这种特定用途。你最好的选择就是尽量避免错误。基于范围的 for
(或 std::for_each
的使用)会在这里帮助你,因为这两者都隐藏了迭代器。
关于c++ - 迭代器使用的编译时间验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12678214/