Main Content

MISRA C++:2023 Rule 28.6.4

The result of std::remove, std::remove_if, std::unique and empty shall be used

Since R2024b

Description

Rule Definition

The result of std::remove, std::remove_if, std::unique and empty shall be used.

Rationale

The rule prevents you from making the incorrect assumption that the functions std::remove(), std::remove_if(), std::unique(), and empty() remove items from a container.

Functions covered by this rule do not remove elements from a container. For example, this invocation of std::remove() does not remove any instance of 2 from the vector numsV:

    std::vector<int> numsV = {1, 2, 3, 4, 5, 2, 2, 6};
    
    // Remove all instances of 2
    auto newEnd = std::remove(numsV.begin(), numsV.end(), 2);
Instead, the function shifts elements that are not marked for removal toward the beginning of the container range and returns an iterator to one past this reduced range. You can pass this iterator to a function such as std::erase() to actually remove the elements from the container:
numsV.erase(newEnd, numsV.end());

Polyspace Implementation

The rule checker reports violations on invocations of std::remove(), std::remove_if(), std::unique(), and empty() if their return values are not assigned to a variable or cast to void.

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <algorithm>
#include <vector>

int main() {
    std::vector<int> numsV = {1, 2, 3, 4, 5, 2, 2, 6};
    
    std::remove(numsV.begin(), numsV.end(), 2); //Noncompliant
    
    auto newEnd = std::remove(numsV.begin(), numsV.end(), 2); //Compliant
    numsV.erase(newEnd, numsV.end());  
}

In this example:

  • The first call to std::remove() is noncompliant because the return value is not assigned to a variable.

  • The second call is compliant because the return value is assigned to a variable that is later used to actually remove all instances of 2 from the vector numsV.

Check Information

Group: Algorithms Library
Category: Required

Version History

Introduced in R2024b