Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

c++ - Is it safe to capture a member reference if the class storing the original reference goes out of scope?

Consider this:

#include <iostream>
#include <functional>

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

struct Foo
{
   int& x;

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

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

   task();
}

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 << '
'; };
   }
};

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.

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 << '
'; };
   }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...