Main Content

AUTOSAR C++14 Rule A18-9-1

The std::bind shall not be used

Description

Rule Definition

The std::bind shall not be used.

Rationale

std::bind takes a callable object, such as a function object, and produces a forwarding call wrapper for this object. Calling the wrapper invokes the object with some of the object arguments bound to arguments you specify in the wrapper. For instance, in this code snippet, foo is called through bar with the first (second) argument of bar bound to the second (first) argument of foo.

int foo(int, int);
auto bar = std::bind(foo, _2, _1);
bar(10, 20); //call to foo(20, 10)
The use of std::bind results in a less readable function call. A developer that is unfamiliar with foo would need to see the declaration of foo to understand how to pass arguments to bar, and might confuse one function parameter with another. In addition, a compiler is less likely to inline a function that you create using std::bind.

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 <cstdint>polys
#include <functional>
class A
{
//...
};
void func(A const& a, double y) noexcept
{
//...
}
void func1() noexcept
{
    double arg2 = 0.0;
    auto bind_fn = std::bind(&func, std::placeholders::_1, arg2); // Non-compliant
    // ...
    A const a{};
    bind_fn(a);
}
void func2() noexcept
{
    auto lambda_fn = [](A const & a) -> void { // Compliant
        double arg2 = 0.0;
        func(a, arg2);
    }; // Compliant
    // ...
    A const a{};
    lambda_fn(a);
}

In this example, func is called through bind_fn with the only argument of bind_fn bound to the first argument of func. It might be unclear to a developer that arg2 in the definition of bind_fn is the second argument of func. For a more readable code, use lambda expressions instead. The call to func with two arguments is clearer in the definition of lambda_fn.

Check Information

Group: 18 Language Support Library
Category: Required, Automated

Version History

Introduced in R2019b