如果存储原始引用的类超出范围,捕获成员引用是否安全? [英] Is it safe to capture a member reference if the class storing the original reference goes out of scope?

查看:73
本文介绍了如果存储原始引用的类超出范围,捕获成员引用是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下内容:

#include <iostream>
#include <functional>

std::function<void()> task;
int x = 42;

struct Foo
{
   int& x;

   void bar()
   {
      task = [=]() { std::cout << x << '\n'; };
   }
};

int main()
{
   {
      Foo f{x};
      f.bar();
   }

   task();
}

我的直觉是,执行任务时实际的参照对象仍然存在,当遇到lambda时,我们会得到一个新绑定的引用,一切都很好。

My instinct was that, as the actual referent still exists when the task is executed, we get a newly-bound reference at the time the lambda is encountered and everything is fine.

但是,在我的GCC 4.8.5(CentOS 7)上,我我看到某个行为(在更复杂的程序中)表明它是UB,因为 f 和引用 fx 本身已经死了。

However, on my GCC 4.8.5 (CentOS 7), I'm seeing some behaviour (in a more complex program) that suggests this is instead UB because f, and the reference f.x itself, have died. Is that right?

推荐答案

要捕获成员引用,您需要使用以下语法(在C ++ 14中引入):

To capture a member reference you need to utilize the following syntax (introduced in C++14):

struct Foo
{
   int & m_x;

   void bar()
   {
      task = [&l_x = this->m_x]() { std::cout << l_x << '\n'; };
   }
};

这样 l_x int& 存储在闭包中,并引用相同的 int m_x 正在引用并且不受 Foo 超出范围的影响。

this way l_x is an int & stored in closure and referring to the same int value m_x was referring and is not affected by the Foo going out of scope.

在C ++ 11中,我们可以解决而是通过捕获指针来丢失此功能:

In C++11 we can workaround this feature being missing by value-capturing a pointer instead:

struct Foo
{
   int & m_x;

   void bar()
   {
      int * p_x = &m_x;
      task = [=]() { std::cout << *p_x << '\n'; };
   }
};

这篇关于如果存储原始引用的类超出范围,捕获成员引用是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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