lambda:应该捕获const引用通过引用yield未定义的行为? [英] lambda: should capturing const reference by reference yield undefined behaviour?

查看:223
本文介绍了lambda:应该捕获const引用通过引用yield未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在我的代码中发现了一个令人讨厌的错误,因为我通过引用捕获了一个字符串的const引用。到lambda运行的时候,原始的字符串对象已经很久了,引用的值是空的,而目的是它将包含原始字符串的值,因此bug。

I just found a nasty bug in my code because I captured a const reference to a string by reference. By the time the lambda was run the original string object was already long gone and the referenced value was empty whereas the purpose was that it would contains the value of the original string, hence the bug.

让我感到烦恼的是,这没有在运行时调用崩溃:毕竟,这不应该是未定义的行为,因为afaik有一个悬挂的引用?此外,当在调试器下查看id时,它甚至看起来不像垃圾,而是像一个正确构造的空字符串。

What baffles me is that this did not invoke a crash at runtime: after all, shouldn't this be undefined behaviour since afaik there is a dangling reference? Moreover when looking at id under the debugger, it doesn't even look like garbage but just like a properly constructed empty string.

这里是测试用例;这只是打印一个空行:

Here's the test case; this just prints an empty line:

typedef std::vector< std::function< void() > > functions;

void AddFunction( const std::string& id, functions& funs )
{
  funs.push_back( [&id] ()
    {
        //the type of id is const std::string&, but there
        //is no object to reference. UB?
      std::cout << id << std::endl;
    } );
}

int main()
{
  functions funs;
  AddFunction( "id", funs );
  funs[ 0 ]();
}


推荐答案

未定义的行为意味着要求应该发生什么。没有要求它应该崩溃。无论你悬挂的引用指向什么内存,没有理由不应该包含看起来像一个空字符串的东西,并且似乎是 string 在该状态下离开内存。

Undefined behavior means there is no requirement what should happen. There is no requirement that it should crash. Whatever memory your dangling reference points at, there's no reason it shouldn't contain something that looks like an empty string, and it's plausible that the destructor of string leaves the memory in that state.

这篇关于lambda:应该捕获const引用通过引用yield未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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