![]() |
Rule 0.1.2 - missing exceptions and advisory ? - Printable Version +- MISRA Discussion Forums (https://forum.misra.org.uk) +-- Forum: MISRA C++ (https://forum.misra.org.uk/forumdisplay.php?fid=18) +--- Forum: MISRA C++:2023 guidelines (https://forum.misra.org.uk/forumdisplay.php?fid=188) +---- Forum: 4.0 Language independent issues (https://forum.misra.org.uk/forumdisplay.php?fid=189) +---- Thread: Rule 0.1.2 - missing exceptions and advisory ? (/showthread.php?tid=1746) |
Rule 0.1.2 - missing exceptions and advisory ? - kth - 07-08-2025 Hi, The amplification of MISRA C++:2023 rule 0.1.2 states that “This rule only applies when the function is called explicitly using function call syntax”. Consequently, operators like “+=” are out of scope so in the following code the modification of the std::string object with “+=” is fine and the usage of append, without checking the returned reference, is a violation of this required rule: Code: void example1() { The function append of std::string (std::basic_string) and the operator+= append additional characters to the end of the string. Both return a reference to “*this”. Both throw std::length_error if the operation would cause size() to exceed max_size() and provide the strong exception safety guarantee. So, there is no real difference between using “+=” or “append” in terms of safety or code quality. If one wants to write compliant code, example1 needs to be refactored to use a void cast to ignore the result: Code: void example1_compliant_version() { That would implicitly force developers to always prefer operators like “+=” over functions like “append” as the alternatives make the code harder to read or lead to additional effort (deviations need to be justified). If one decides to rework this kind of code to a “fluent API style” that could lead to extra copies: Code: std::string BuildFailureMsg(std::string_view name, std::string_view reason) { Consequently, existing code that uses append needs to be refactored to use “+=”. A huge refactoring effort for large code bases, but without any real benefit. Also, it might lead to the negative effect that developers that uses std::vector prefer “push_back” over “emplace_back”, as with C++17 std::vector::emplace_back returns a reference (example3). Other alternatives might lead to less efficient code. Our questions:
|