MISRA Discussion Forums
A5-0-4 - Does the rule apply to range-based for loops? - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C++ (https://forum.misra.org.uk/forumdisplay.php?fid=18)
+--- Forum: AUTOSAR C++:2014 rules (https://forum.misra.org.uk/forumdisplay.php?fid=185)
+--- Thread: A5-0-4 - Does the rule apply to range-based for loops? (/showthread.php?tid=1589)



A5-0-4 - Does the rule apply to range-based for loops? - cgpzs - 04-11-2021

Hi,

Does rule A5-0-4 apply to range-based `for` loops? Technically, range-based `for` loops are syntactic sugar for iterator-based loops, so technically pointer arithmetic is happening under the hood. Consider this example:

Code:
struct Foo /* final */
{
    int x;
    int y;
};

std::vector<Foo> v;

// Fill v...


for (x : v)  // A5-0-4 violated here?
{
   ...
}

The easy solution is to make `Foo` `final`, of course. But what about classes we don't have control over, like STL classes?


Code:
std::vector<std::vector<int>>
std::vector<std::unique_ptr<int>>

A range-based `for` loop would be performing pointer arithmetic over `std::vector<int>*` and `std::unique_ptr<int>*`. These classes are not `final`. Would that then violate A5-0-4?

Our static analyzer is flagging these use cases as non-compliant, but it feels overly strict. What's your view on this?

Thanks!


RE: A5-0-4 - Does the rule apply to range-based for loops? - misra cpp - 12-11-2021

The short answer is that A5-0-4 is not intended to apply to range-based for loops applied to containers


RE: A5-0-4 - Does the rule apply to range-based for loops? - cgpzs - 15-11-2021

Great, thanks for the quick reply!


RE: A5-0-4 - Does the rule apply to range-based for loops? - misra cpp - 11-01-2022

This thread is now closed

Anyone having a related question, .please start a new thread