1 year ago

#364353

test-img

Hidayat Rzayev

Passing the tuple by reference into lambda causes null pointer dereference warning

I have the following piece of code:

boost::circular_buffer<std::tuple<float, float, float>> foo;
foo.push_front(std::make_tuple(3.1f, 1.5f, 1.2f));
foo.push_front(std::make_tuple(3.6f, 1.1f, 1.7f));
foo.push_front(std::make_tuple(3.2f, 1.1f, 1.9f));

const float bar = 3.5f;

// find the first tuple for which the first element is greater than bar
auto firstGreater = std::find_if(foo.begin(), foo.end(), [bar](const auto &t) {
    return std::get<0>(t) > bar;
});

When compiling this code with GCC version 7.5.0 or 9.3.0 (did not try with other versions) with a flag -Wnull-dereference, I get a warning in the return statement of the lambda:

error: potential null pointer dereference [-Werror=null-dereference]
139 |                         return std::get<0>(t) > bar;
    |                                ~~~~~~~~~~~~~~~^~~~~

Interestingly enough, when the tuple is passed to the lambda by value instead of by reference, the warning is gone:

auto firstGreater = std::find_if(foo.begin(), foo.end(), [bar](auto t) {
    return std::get<0>(t) > bar;
});

I am trying to understand why that would be the case since a reference cannot point to nothing, but can't figure out the root of the issue. Any ideas why this might happen?

Note: the above snippet is just a sample, but it does reflect the essence of what is going on in the real code. Although it may not be enough to reproduce the warning

c++

lambda

pass-by-reference

compiler-warnings

0 Answers

Your Answer

Accepted video resources