给从函数返回的右值引用赋值 [英] Assign a value to an rvalue reference returned from function

查看:152
本文介绍了给从函数返回的右值引用赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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没有检测到任何东西。也许编译可以帮助我创建另一个不可见变量,例如

When function calling finished, the object std::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(std::vector {1, 2, 3, 4, 5}, 2)};
invisible_value = 9;

如果我的猜测不正确,我想知道为什么将值赋给从函数返回的右值引用工作,当临时对象 index(std :: vector {1、2、3、4、5},2)被破坏时。

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(std::vector {1, 2, 3, 4, 5}, 2) will be destroyed.

这个想法起源于《有效的现代C ++》,第3项:理解 decltype

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

推荐答案

您说过函数调用完成后,对象向量{1,2,3,4,5}将被销毁,但这是不正确的。直到语句结束(即下一行代码),才删除为函数调用创建的临时目录。否则,想象通过临时字符串的c_str()会破坏多少代码。

You said "When function calling finished, the object vector {1, 2, 3, 4, 5} will be destroyed" but that is untrue. The temporary created for the function call is not deleted until the statement ends, i.e. the next line of code. Otherwise imagine how much code would break that passes c_str() of a temporary string.

这篇关于给从函数返回的右值引用赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆