将lambda存储为std :: function时出现分段错误

Tom*_*ang 1 c++ lambda std-function

以下代码给出了分段错误.调试之后,我发现问题可以通过将lambda声明为auto而不是Function来解决.为什么会这样?

#include <functional>
#include <iostream>
#include <vector>

typedef std::vector<double> Vec;
typedef std::function<const Vec&(Vec)> Function;


int main()
{
     //Function func = [](const Vec& a)->Vec /*this give me segfault*/
     auto func = [](const Vec& a)->Vec /*this work just fine??*/
         {
              Vec b(2);
              b[0] = a[0] + a[1];
              b[1] = a[0] - a[0];
              return b;
         };
     Vec b = func(Vec{1,2});
     std::cout << b[0] << " " << b[1] << "\n";
     return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果我可以将它声明为Function,那将是很好的,因为我想将这个lambda表达式传递给其他类.

当func声明为Function时,我所遇到的错误是:

程序接收信号SIGSEGV,分段故障.0x0000000000401896在std :: vector> :: size(this = 0x0)/usr/include/c++/5/bits/stl_vector.h:655 655 {return size_type(this - > _ M_impl._M_finish - this - > _ M_impl._M_start ); }
(gdb)回溯
#0 0x0000000000401896在std :: vector> :: size(this = 0x0)/usr/include/c++/
5/bits/stl_vector.h: 655 #1 0x00000000004015aa in std :: vector> ::在/usr/include/c++/5/bits/stl_vector.h:320的向量(这= 0x7fffffffdc50,__ =)在test.cxx的
main()中的#0x0000000000400d12:18

Sto*_*ica 6

const Vec&(Vec)相当于一个看起来像这样的lambda (Vec) -> const Vec&.你通过了(const Vec&) -> Vec.

std::function 由于调用序列包含有效转换而接受它(您可以将值传递给期望const引用的函数).

分段错误最有可能是你的lambda(临时)的返回值固有的未定义行为被绑定到std::function's中的const引用operator(); 该引用正在返回之外std::function,立即使其成为悬挂引用.