#include <utility>
template <typename Container>
decltype(auto) index(Container &&arr, int n) {
return std::forward<Container>(arr)[n];
}
进行函数调用:
#include <vector>
index(std::vector {1, 2, 3, 4, 5}, 2) = 0;
当函数调用完成后,对象std::vector {1, 2, 3, 4, 5}
将被销毁,为已释放的地址分配一个值将导致未定义的行为。但上面的代码运行良好,valgrind 没有检测到任何结果。也许编译可以帮助我制作另一个不可见的变量,例如
auto &&invisible_value {index(std::vector {1, 2, 3, 4, 5}, 2)};
invisible_value = 9;
如果我的猜测不正确,我想知道为什么为函数返回的右值引用赋值是有效的,以及临时对象何时起作用index(std::vector {1, 2, 3, 4, 5}, 2)
将被摧毁。
这个想法来源于《Effective Modern C++》,Item3:理解decltype
.