C++ 程序在向量析构函数中挂起
C++ program hangs in vector destructor
我有一个带有预处理器的字段的结构#define:
struct MyType {
int somedata;
#ifdef HAS_INDEX
int index;
#endif
}
当我向向量添加实例时,程序在第一次重新分配时挂起:
vector<MyType> myData;
myData.reserve(4);
myData.push_back(MyType{0,0});
myData.push_back(MyType{0,1});
myData.push_back(MyType{0,2});
myData.push_back(MyType{0,3});
myData.push_back(MyType{0,4}); // Program hangs
我在之前的行上设置了一个断点,然后单步执行了附加的过程。当旧的向量存储被释放时,破坏向量的函数似乎在 Microsoft Visual Studio 2015 编译器的 xmemory0 处进入无限循环:
// TEMPLATE FUNCTION _Destroy_range WITH ALLOC
template<class _Alloc,
class _Ptr = typename _Wrap_alloc<_Alloc>::pointer> inline
void _Destroy_range1(_Ptr _First, _Ptr _Last, _Wrap_alloc<_Alloc>& _Al, false_type)
{ // destroy [_First, _Last), no special optimization
for (; _First != _Last; ++_First) // <----- infinite loop here with _First > _Last
_Al.destroy(_Unfancy(_First));
}
为什么程序挂在那里?
(为清晰显示问题而编辑的问题)
经过大量调试,我发现了问题。
我在结构中有一个定义,它向结构添加了一个额外的成员变量。
当我使用该函数构建一个库并将 header 包含在我的程序中时,定义仅在其中一个项目中设置。
所以第二个项目删除了for (; _First != _Last; ++_First)
循环中的数据,但使用的数据结构比用于分配内存的结构多了一个成员。所以循环会跳过实际数据的末尾。然后得到_Last < _First
,循环并没有终止,因为_First
只是在循环中增加了
我有一个带有预处理器的字段的结构#define:
struct MyType {
int somedata;
#ifdef HAS_INDEX
int index;
#endif
}
当我向向量添加实例时,程序在第一次重新分配时挂起:
vector<MyType> myData;
myData.reserve(4);
myData.push_back(MyType{0,0});
myData.push_back(MyType{0,1});
myData.push_back(MyType{0,2});
myData.push_back(MyType{0,3});
myData.push_back(MyType{0,4}); // Program hangs
我在之前的行上设置了一个断点,然后单步执行了附加的过程。当旧的向量存储被释放时,破坏向量的函数似乎在 Microsoft Visual Studio 2015 编译器的 xmemory0 处进入无限循环:
// TEMPLATE FUNCTION _Destroy_range WITH ALLOC
template<class _Alloc,
class _Ptr = typename _Wrap_alloc<_Alloc>::pointer> inline
void _Destroy_range1(_Ptr _First, _Ptr _Last, _Wrap_alloc<_Alloc>& _Al, false_type)
{ // destroy [_First, _Last), no special optimization
for (; _First != _Last; ++_First) // <----- infinite loop here with _First > _Last
_Al.destroy(_Unfancy(_First));
}
为什么程序挂在那里?
(为清晰显示问题而编辑的问题)
经过大量调试,我发现了问题。 我在结构中有一个定义,它向结构添加了一个额外的成员变量。 当我使用该函数构建一个库并将 header 包含在我的程序中时,定义仅在其中一个项目中设置。
所以第二个项目删除了for (; _First != _Last; ++_First)
循环中的数据,但使用的数据结构比用于分配内存的结构多了一个成员。所以循环会跳过实际数据的末尾。然后得到_Last < _First
,循环并没有终止,因为_First
只是在循环中增加了