代码之家  ›  专栏  ›  技术社区  ›  allo

C++程序挂起在向量析构函数中

  •  -2
  • allo  · 技术社区  · 7 年前

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

    (为了清晰起见,对问题进行了编辑,以显示问题)

    1 回复  |  直到 7 年前
        1
  •  0
  •   allo    7 年前

    经过多次调试,我发现了这个问题。 当我用该函数构建库并在程序中包含标题时,定义只在其中一个项目中设置。

    所以第二个项目删除了 for (; _First != _Last; ++_First) _Last < _First 循环不会终止,因为 _First 仅在循环中增加。