Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

structured bindings with std::minmax and rvalues

Tags:

I ran into a rather subtle bug when using std::minmax with structured bindings. It appears that passed rvalues will not always be copied as one might expect. Originally I was using a T operator[]() const on a custom container, but it seems to be the same with a literal integer.

#include <algorithm> #include <cstdio> #include <tuple>  int main() {     auto [amin, amax] = std::minmax(3, 6);     printf("%d,%d\n", amin, amax); // undefined,undefined      int bmin, bmax;     std::tie(bmin, bmax) = std::minmax(3, 6);     printf("%d,%d\n", bmin, bmax); // 3,6 } 

Using GCC 8.1.1 with -O1 -Wuninitialized will result in 0,0 being printed as first line and:

warning: ‘<anonymous>’ is used uninitialized in this function [-Wuninitialized] 

Clang 6.0.1 at -O2 will also give a wrong first result with no warning.

At -O0 GCC gives a correct result and no warning. For clang the result appears to be correct at -O1 or -O0.

Should not the first and second line be equivalent in the sense that the rvalue is still valid for being copied?

Also, why does this depend on the optimization level? Particularly I was surprised that GCC issues no warning.

like image 601
Zulan Avatar asked Jul 24 '18 16:07

Zulan


1 Answers

What's important to note in auto [amin, amax] is that the auto, auto& and so forth are applied on the made up object e that is initialized with the return value of std::minmax, which is a pair. It's essentially this:

auto e = std::minmax(3, 6);  auto&& amin = std::get<0>(e); auto&& amax = std::get<1>(e); 

The actual types of amin and amax are references that refer to whatever std::get<0> and std::get<1> return for that pair object. And they themselves return references to objects long gone!

When you use std::tie, you are doing assignment to existing objects (passed by reference). The rvalues don't need to live longer than the assignment expressions in which they come into being.


As a work around, you can use something like this (not production quality) function:

template<typename T1, typename T2> auto as_value(std::pair<T1, T2> in) {     using U1 = std::decay_t<T1>;     using U2 = std::decay_t<T2>;     return std::pair<U1, U2>(in); } 

It ensures the pair holds value types. When used like this:

auto [amin, amax] = as_value(std::minmax(3, 6)); 

We now get a copy made, and the structured bindings refer to those copies.

like image 137
StoryTeller - Unslander Monica Avatar answered Oct 21 '22 20:10

StoryTeller - Unslander Monica