在抛出'std :: bad_alloc'的实例后终止调用

时间:2012-10-10 10:54:16

标签: c++ c++11

这是我的设置(煮沸了)。我有一个“布局功能”:

  struct LayoutFunc {
    LayoutFunc( int limit , int value ) { lim.push_back(limit); val.push_back(value); }
    //LayoutFunc(LayoutFunc&& func) : lim(func.lim),val(func.val) {}
    LayoutFunc(const LayoutFunc& func) : lim(func.lim),val(func.val) {} // error: std::bad_alloc
    LayoutFunc(const std::vector<int>& lim_, 
               const std::vector<int>& val_ ) : lim(lim_),val(val_) {}
    LayoutFunc curry( int limit , int value ) const {
      std::vector<int> rlim(lim);
      std::vector<int> rval(val);
      rlim.push_back(limit);
      rval.push_back(value);
      LayoutFunc ret(rlim,rval);
      return ret;
    };
    std::vector<int> lim;
    std::vector<int> val;
  };

然后我有一个使用LayoutFunc的课程:

template<class T> class A
{
public:
  A( const LayoutFunc& lf_ ) : lf(lf_), member( lf.curry(1,0) ) {}
  A(const A& a): lf(lf), member(a.function) {}  // corresponds to line 183 in real code
private:
  LayoutFunc lf;
  T member;
};

数据成员的顺序是正确的。还有更多类型,例如class A,它使用稍微不同的数字来“curry”布局功能。我不打印它们以节省空间(它们具有相同的结构,只有不同的数字)。最后我用的是:

A< B< C<int> > > a( LayoutFunc(1,0) );

将根据模板类型顺序构建“curried”布局函数。

现在,可能这个简单的(煮沸的)示例有效。但是,在运行时的实际应用程序中,我在terminate called after throwing an instance of 'std::bad_alloc'的复制构造函数中得到LayoutFunc

我认为设置中存在一个缺陷,即引用临时引用,并且在消费者(在本例中为LayoutFunc的复制构造函数)使用它之前,此临时文件被销毁。这可以解释lim(func.lim),val(func.val)失败。但我无法确定缺陷的位置,因为curry会返回一个真正的lvalue。我也尝试使用移动构造函数并在c ++ 11模式下编译。同样的行为。

这里的回溯:

#0  0x00007ffff6437445 in __GI_raise (sig=<optimised out>) at ../nptl/sysdeps/unix/sysv/linux/raise.c:64
#1  0x00007ffff643abab in __GI_abort () at abort.c:91
#2  0x00007ffff6caa69d in __gnu_cxx::__verbose_terminate_handler() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#3  0x00007ffff6ca8846 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#4  0x00007ffff6ca8873 in std::terminate() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#5  0x00007ffff6ca896e in __cxa_throw () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#6  0x00007ffff6c556a2 in std::__throw_bad_alloc() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#7  0x00000000004089f6 in allocate (__n=18446744073709551592, this=0x7fffffffdaf8) at /usr/include/c++/4.6/ext/new_allocator.h:90
#8  _M_allocate (__n=18446744073709551592, this=0x7fffffffdaf8) at /usr/include/c++/4.6/bits/stl_vector.h:150
#9  _Vector_base (__a=..., __n=18446744073709551592, this=0x7fffffffdaf8) at /usr/include/c++/4.6/bits/stl_vector.h:123
#10 vector (__x=..., this=0x7fffffffdaf8) at /usr/include/c++/4.6/bits/stl_vector.h:279
#11 LayoutFunc (func=..., this=0x7fffffffdae0) at layoutfunc.h:17
#12 A (a=..., this=0x7fffffffdad0) at A.h:183

A.h:183是A的复制构造函数:

  A(const A& a): lf(lf), member(a.function) {}

1 个答案:

答案 0 :(得分:3)

A(const A& a): lf(lf), member(a.function) {}

应该是

A(const A& a): lf(a.lf), member(a.function) {}

BЈовић评论指出了我找到这个bug的方向。如果您发布答案,请发送+1BЈовић。还要+1才能理解BT

相关问题