gpt4 book ai didi

c++ - 如何在编译或运行时检测错误的迭代器使用

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:03:48 25 4
gpt4 key购买 nike

我刚刚在一些遗留代码中发现了对不同容器的迭代器之间的 std::distance 的严重滥用。包括代码之类的东西。现在恐怕有人可能在代码的其他部分犯了同样的错误。

有没有办法在编译或运行时检测到这种错误?

// bad code to explain the problem
std::vector<int> v1={1};
auto iterv1=v1.begin();
std::vector<int> v2=v1;
int nDist=std::distance(v2.begin(),iterv1); // error distance calculated between 2 containers

最佳答案

因此,如果我在 g++ 中尝试这个示例,我将使用 -D_GLIBCXX_DEBUG 进行编译:

    std::vector<int>
v1, v2 ;

std::distance( v1.begin(), v2.end() ) ;

我在运行时看到了这个错误:

error: attempt to compute the different between two iterators from
different sequences.

有更多的输出,但我认为这应该涵盖它。上一个线程 covers the same thing for Visual Studio .

关于c++ - 如何在编译或运行时检测错误的迭代器使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15434243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com