请您解释一下,在这种情况下,如何存储conditionalVariable,以便在条件块外调用check_calls_on_current_floor时使用?
std::function<bool()> check_calls_on_current_floor;
if (/*Some condition*/)
{
const int conditionalVariable = /*some value*/;
check_calls_on_current_floor = [&](){
return conditionalVariable == 10; };
}
check_calls_on_current_floor();在这种情况下,我们似乎可以在条件块之外访问这个变量,以防我们从那里得到lambda。
发布于 2013-11-13 05:03:31
这是个悬空的参考资料。在if块之后进行调用是未定义的行为。它非常类似于从函数中返回对局部变量的引用。更类似的是:
struct ref_holder
{
ref_holder(const int & r) :ref(r) {}
const int & ref;
};
int main()
{
std::unique_ptr<ref_holder> ptr;
if (true)
{
const int conditionalVariable = 10;
ptr.reset(new ref_holder(conditionalVariable));
}
ptr->ref == 10; // undefined behavior
}发布于 2013-11-13 05:07:36
它有点类似于这样:
int x = 0;
int* z = &x;
if (condition)
{
int y = 1;
z = &y;
}如果条件成立,那么z将指向已超出范围的y。
https://stackoverflow.com/questions/19945660
复制相似问题