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

terminate called after throwing an instance of 'std::bad_alloc'

本文关键字:实例 调用 alloc 终止 bad std      更新时间:2023-10-16

这是我的设置(简单来说)。我有一个"布局功能":

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这样的类型,它们使用稍微不同的数字来"咖喱"布局函数。我不会在这里打印它们以节省空间(它们的结构相同,只是编号不同)。最后,我使用了类似的东西:

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

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

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

我认为设置中有一个缺陷,它与引用一个临时文件有关,而这个临时文件在使用者(在本例中是LayoutFunc的复制构造函数)使用它之前就被销毁了。这将解释lim(func.lim),val(func.val)失败的原因。但我看不出缺陷在哪里,尤其是因为curry返回了一个真正的lvalue。我还用move构造函数进行了尝试,并在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) {}
A(const A& a): lf(lf), member(a.function) {}

应该是

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

B的评论为我找到这个bug指明了方向。如果你发布一个答案,+1 B。还有+1,让他理解BT