mardi 2 juin 2020

Assign a value to an rvalue reference returned from function

#include <utility>
template <typename Container>
decltype(auto) index(Container &&arr, int n) {
    return std::forward<Container>(arr)[n];
}

Make a function call :

#include <vector>
index(vector {1, 2, 3, 4, 5}, 2) = 0;

When function calling finished, the object vector {1, 2, 3, 4, 5} will be destroyed, assigning a value to a deallocated address would cause undefined behaviour. But the above code works well and valgrind detected nothing. Maybe the compile helps me make another invisible variable like

auto &&invisible_value {index(vector {1, 2, 3, 4, 5}, 2)};
invisible_value = 9;

If my guess is incorrect, I want to know why assigning a value to an rvalue reference returned from function is worked and when the temporary object index(vector {1, 2, 3, 4, 5}, 2) will be destroyed.

This idea originated from 《Effective Modern C++》, Item3 : Understand decltype

Thanks!

Aucun commentaire:

Enregistrer un commentaire