#include <utility>
template <typename Container>
decltype(auto) index(Container &&arr, int n) {
return std::forward<Container>(arr)[n];
}
进行函数调用:
#include <vector>
index(vector {1, 2, 3, 4, 5}, 2) = 0;
当函数调用完成时,对象vector {1, 2, 3, 4, 5}
将被破坏,将值分配给释放的地址将导致未定义的行为。但是上面的代码运行良好,并且valgrind没有检测到任何东西。也许编译可以帮助我创建另一个不可见变量,例如
auto &&invisible_value {index(vector {1, 2, 3, 4, 5}, 2)};
invisible_value = 9;
如果我的猜测不正确,我想知道为什么为从函数返回的右值引用分配值是可行的,以及何时将销毁临时对象index(vector {1, 2, 3, 4, 5}, 2)
。
这个想法起源于《有效的现代C ++》,条款3:理解decltype
谢谢!
您说过“函数调用完成后,对象向量{1,2,3,4,5}将被破坏”,但这是不正确的。直到语句结束(即下一行代码),才删除为函数调用创建的临时目录。否则,假设通过临时字符串的c_str()会破坏多少代码。