簡體   English   中英

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));
}

為什么程序掛在那里?

(為清楚起見編輯了問題以顯示問題)

經過大量調試,我發現了問題。 我在結構中有一個定義,它向結構中添加了一個額外的成員變量。 當我使用該函數構建一個庫並將頭文件包含在我的程序中時,定義僅在其中一個項目中設置。

因此,第二個項目刪除了for (; _First != _Last; ++_First)循環中的數據,但數據結構的成員比用於分配內存的結構多一個成員。 所以循環會跳過實際數據的末尾。 然后它得到_Last < _First並且循環不會終止,因為_First僅在循環中增加。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM