Consider this:
考虑一下:
#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();
}
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.
我的直觉是,当执行任务时,实际的引用仍然存在,我们在遇到lambda时得到一个新绑定的引用,一切正常。
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?
然而,在我的GCC 4.8.5 (CentOS 7)中,我看到了一些行为(在一个更复杂的程序中),这表明这是UB,因为f和参考f。x本身,已经死亡。是这样吗?
2 个解决方案
#1
8
To capture a member reference you need to utilize the following syntax (introduced in C++14):
为了捕获成员引用,您需要使用以下语法(在c++ 14中引入):
struct Foo
{
int & m_x;
void bar()
{
task = [&l_x = this->m_x]() { std::cout << l_x << '\n'; };
}
};
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.
这样,l_x是一个int &存储在闭包中并引用m_x引用的相同int值,不受Foo超出范围的影响。
In C++11 we can workaround this feature being missing by value-capturing a pointer instead:
在c++ 11中,我们可以通过捕捉指针来解决这个缺失的特性:
struct Foo
{
int & m_x;
void bar()
{
int * p_x = &m_x;
task = [=]() { std::cout << *p_x << '\n'; };
}
};
#2
3
You can capture a reference member in C++11 by creating a local copy of the reference and explicit capture to avoid capturing this
:
您可以通过创建引用的本地副本和显式捕获来捕获c++ 11中的引用成员,以避免捕获以下内容:
void bar()
{
decltype(x) rx = x; // Preserve reference-ness of x.
static_assert(std::is_reference<decltype(rx)>::value, "rx must be a reference.");
task = [&rx]() { std::cout << rx << ' ' << &rx << '\n'; }; // Only capture rx by reference.
}
#1
8
To capture a member reference you need to utilize the following syntax (introduced in C++14):
为了捕获成员引用,您需要使用以下语法(在c++ 14中引入):
struct Foo
{
int & m_x;
void bar()
{
task = [&l_x = this->m_x]() { std::cout << l_x << '\n'; };
}
};
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.
这样,l_x是一个int &存储在闭包中并引用m_x引用的相同int值,不受Foo超出范围的影响。
In C++11 we can workaround this feature being missing by value-capturing a pointer instead:
在c++ 11中,我们可以通过捕捉指针来解决这个缺失的特性:
struct Foo
{
int & m_x;
void bar()
{
int * p_x = &m_x;
task = [=]() { std::cout << *p_x << '\n'; };
}
};
#2
3
You can capture a reference member in C++11 by creating a local copy of the reference and explicit capture to avoid capturing this
:
您可以通过创建引用的本地副本和显式捕获来捕获c++ 11中的引用成员,以避免捕获以下内容:
void bar()
{
decltype(x) rx = x; // Preserve reference-ness of x.
static_assert(std::is_reference<decltype(rx)>::value, "rx must be a reference.");
task = [&rx]() { std::cout << rx << ' ' << &rx << '\n'; }; // Only capture rx by reference.
}