c – 在for循环中重新排序测试条件:编译器错误?

c – 在for循环中重新排序测试条件:编译器错误?,第1张

概述我有一个存储在数组中的树,我正在尝试找到一个特定的节点: std::vector<Node> nodes = ...const unsigned short sentinel = -1;unsigned short index = 0;for (Node* node = &nodes[index]; // root node index != sentinel; node 我有一个存储在数组中的树,我正在尝试找到一个特定的节点:
std::vector<Node> nodes = ...const unsigned short sentinel = -1;unsigned short index = 0;for (Node* node = &nodes[index]; // root node     index != sentinel;     node = &nodes[index]){    if (foo(*node)) {       index = node->left;    } else {       index = node->right;    }}

换句话说,没什么特别的.但是,MSVC 2012失败,尝试访问超出范围的节点[sentinel].事实证明,它首先计算& nodes [index],然后测试索引. (调试模式,无优化).

对我来说,这看起来像代码生成错误,但我至少在十年内没有看到过这样的错误.这是简单的未经优化的代码.当然,即使重新排列,在测试索引之前实际上并未使用节点,并且在x86上具有这样的越界指针并不是非常不安全,但是MSVC的向量<>合法地断言该非法指数.

干净的构造并再次检查组件;它是可重复的.树也不是空的,总是有一个根节点.

我忽略了什么,或者这真的是一个严重的编译器错误?

解决方法 你的代码重写为while循环就像
Node* node = &nodes[index]; // root nodewhile(index != sentinel){    {        if (foo(*node)) {           index = node->left;        } else {           index = node->right;        }    }    node = &nodes[index];}

最后一行可能是对节点[-1]的访问.

我会把你的循环改写成

unsigned short index = 0;do{    Node* node = &nodes[index];    if (foo(*node)) {       index = node->left;    } else {       index = node->right;    }} while(index != sentinel);
总结

以上是内存溢出为你收集整理的c – 在for循环中重新排序测试条件:编译器错误?全部内容,希望文章能够帮你解决c – 在for循环中重新排序测试条件:编译器错误?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1240927.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存