悬空参考溶液

发布于 2025-01-14 19:52:05 字数 1111 浏览 6 评论 0 原文

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

}

T&& operator[](std::size_t n) && noexcept {std::cout<<"move"<<std::endl; return std::move(vec[n]); }
I cannot get the expected result in this part.
I predict a dangling reference happens.

T operator[](std::size_t n) && noexcept {std::cout<<"move"<<std::endl; return std::move(vec[n]); }
This works well.
Why doesn't T&& increase lifetime?

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

万人眼中万个我 2025-01-21 19:52:06

对于自动&& 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.

In general, the lifetime of a temporary cannot be further extended by "passing it on": a second reference, initialized from the reference variable or data member to which the temporary was bound, does not affect its lifetime.

On the other hand, if you change the return type of operator[] to T, then what it returns (i.e. my_vector<int>{1, 2, 3}[0]) is a temporary and gets bound to vec, then its lifetime is extended to the lifetime of vec.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文