use*_*168 4 c++ windows winapi visual-studio-2008
我在Windows上,我正在用VS2008构建一个C++项目.我正在尝试替换new/delete/malloc/free等.这是有效的,即我的替换被调用.
但是我的替换分配器需要初始化.到目前为止,我已经将它定义为.cpp文件中的全局变量,并在其中定义了#pragma init_seg(lib).
直到最近std :: locale开始初始化时才开始工作,这在我的分配器初始化之前调用了new.所以我紧张地将我的allocator的全局变量移动到编译器段,即#pragma init_seg(编译器).
这工作了一点,然后我决定覆盖malloc.现在我在_tmainCRTStartup中的__crtGetStringTypeA_stat中获得了一个malloc调用,甚至在编译器段中的全局变量已经初始化之前.
有没有办法让我的变量在CRT启动之前被实例化.我唯一能想到的是重建我的crt lib并尝试一些如何在那里插入我的初始化代码.我认为必须有一个crt清理功能?
是否有更容易的途径和/或我在这里缺少的明显的东西?
您正在使用一个static storage duration
对象.
但是你的初始化顺序有问题.
要解决此问题,请使用在函数范围内定义的静态存储持续时间对象.
MyAllocator& getAllocator()
{
static MyAllocator allocator; // Note the static here.
// It has the appropriate lifespan and will be destoryed.
// and is automatically constructed the first time this
// function is called.
return allocator;
}
Run Code Online (Sandbox Code Playgroud)
现在你的new/delete/etc版本可以通过调用getAllocator()获得对分配器的引用.这将保证对象被正确初始化(假设MyAllocator具有正确的构造函数).