迭代器使用的编译时验证

Compile time validation for iterator usage?

本文关键字:验证 编译 迭代器      更新时间:2023-10-16

我有以下一段粗心的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 早期部分采用)已经纠正了"擦除"实际上需要"const_iterator"的行为。

提前感谢您的任何宝贵意见。

C++不

是一种读心术语言。它所知道的只是类型。它知道erase需要一个迭代器。它知道i是同一类型的迭代器。因此,就编译器的C++规则而言,调用erase(i)是合法的。

编译器无法知道您要做什么。编译器也没有办法知道i的内容不适合erase的这种特定用途。你最好的选择是尽量避免错误。基于范围的for(或使用std::for_each)将在这里为您提供帮助,因为两者都隐藏了迭代器。