悬空参考溶液
T&&运算符[](std::size_t n) && noexcept {std::cout<<"移动"<
我在这部分无法得到预期的结果。
我预测会发生悬空引用。
T 运算符[](std::size_t n) && noexcept {std::cout<<"移动"<
这效果很好。
为什么 T&&增加寿命?
#include <iostream>
#include <stdlib.h>
#include<vector>
template<typename T, typename Alloc = std::allocator<T>>
class my_vector
{
std::vector<T, Alloc> vec;
public:
my_vector(std::initializer_list<T> init) : vec{init} {}
T&& operator[](std::size_t n) && noexcept {std::cout<<"move"<<std::endl; return std::move(vec[n]); } // moveしたものを参照するとごみを参照してることになる
//T operator[](std::size_t n) && noexcept {std::cout<<"move"<<std::endl; return std::move(vec[n]); }
};
int main()
{
auto&& vec = my_vector<int>{1, 2, 3}[0]; //case3 move
std::cout<<vec<<std::endl; //0
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于
自动&& vec = my_vector{1, 2, 3}[0];
,引用未绑定到临时变量(即my_vector{1, 2, 3}
>) 直接,它的 生命周期不会延长。另一方面,如果将
operator[]
的返回类型更改为T
,那么它会返回什么(即my_vector{1, 2, 3}[0]
) 是一个临时变量,并绑定到vec
,然后它的生命周期将延长到vec
的生命周期。For
auto&& vec = my_vector<int>{1, 2, 3}[0];
, the reference isn't bound to the temporary (i.e.my_vector<int>{1, 2, 3}
) directly, its lifetime won't be extended.On the other hand, if you change the return type of
operator[]
toT
, then what it returns (i.e.my_vector<int>{1, 2, 3}[0]
) is a temporary and gets bound tovec
, then its lifetime is extended to the lifetime ofvec
.