2016-06-21 64 views
1

我不能在这里列出一个MCVE,因为它太长了。我在我自己写的STL内存分配器中遇到问题,但在global object [e.q.]中使用时只有。不在函数]:我自己的STL内存分配器的分段错误

class Heap 
{ 
    static FaF::string heapString; 
}; 

FaF::string Heap::heapString("heapString"); 

FaF是我namespace其中string定义如下:

namespace FaF 
{ 
    using string = std::basic_string<char, std::char_traits<char>, Allocator<char>>; 
} 

Allocator是我的STL内存分配器。

Allocator模板我有这样的代码:

T* allocate (std::size_t num, const void* hint = 0) 
{ 
    T * allocatedPointer = static_cast<T*> (getNextAvailableFreePointer(num)); 
    ... 

崩溃是在这条线的功能getNextAvailableFreePointer

mapForMemoryContainer.emplace(alignedMemorySize, MemoryContainer()); 

MemoryContainer只是一个非常简单的结构。

我的问题:

为什么当全球 STL对象是使用我的Allocator程序崩溃?我测试了非常复杂的Allocator类,它工作正常[没有内存泄漏,..]但在这种情况下它崩溃。

甚至在第一行代码main()之前崩溃。

更新:

mapForMemoryContainer是在基类中定义的std::map

class Allocator_Base 
{ 
    public: 
     Allocator_Base() { printf("in Allocator_Base constructor\n"); } 

    protected: 
     static std::map<int, MemoryContainer> mapForMemoryContainer; 
     ... 
} 

而且Allocator模板的定义是这样的:

template <typename T> 
class Allocator : public Allocator_Base 
{ 

这就是全部。文本in Allocator_Base constructor在崩溃之前显示两次。

+0

什么是'mapForMemoryContainer'?它也使用你的分配器吗? – Arunmu

+0

'它甚至在main()'中的第一行代码之前崩溃了你有任何静态初始化顺序问题吗?将需要一些更多的问题 – Arunmu

+0

我很确定这是一个静态初始化的问题。我的猜测是,持有'mapForMemoryContainer'的结构尚未初始化。粘贴核心转储的堆栈跟踪将会很有帮助。 – Arunmu

回答

0

我现在总结类似的回答所有的评论,但答案属于用户n.m.

  1. 这是一个static initialization order fiasco(C)n.m.
  2. 我实现了他在这个答案评论和感动所有明智的物体分成get....()功能。

现在它就像一个魅力。

+2

最简单也是最可靠的方法是将静态变量移动到一个函数中。使用'static std :: map &getMemoryMap(){static std :: map memoryMap;返回memoryMap; }'这保证'getMemoryMap'第一次返回之前'memoryMap'的初始化。 –