我将 RTL 用作动态库。这允许在全局命名空间中覆盖新/删除运算符,因为链接器会首先找到我的实现。我可以依靠 malloc() 和 free() 来做分配的事情,但是有像 'new_handlers' 和 'std::nothrow' 对象这样的东西。标准库模板需要 new/delete 运算符的特定行为,但标准库在全局命名空间中对 new/delete 的实现超出了范围!我可以使用来自标准库的另一个 namespace 中的实现吗?
我可能会动态确定标准库的实现地址(在 dll 中)并通过指针调用它,但这不受美化奖励的影响。这仍然有效吗? (我正在使用 borland C++ builder 2006)。
编辑我想问这个问题:
此示例代码的行为是否类似于 RTL 的 operator new(size_t)?还是我理解错了?
void *new_replacement(size_t p_size)
{
void *l_retval = NULL;
while(l_retval == NULL && p_size != 0)
{
l_retval = malloc(p_size);
if (l_retval == NULL)
{
void (*l_handler)() = std::set_new_handler(NULL);
// could not find another way to obtain the current new_handler
if (l_handler == NULL) throw std::bad_alloc();
std::set_new_handler(l_handler);
l_handler();
}
}
return l_retval;
}
最佳答案
你已经 replaced, not overridden默认实现,您不能再调用它。您将不得不重新实现它 - 例如通过使用 malloc()
并处理它的返回值,这并不难。
关于c++ - 在覆盖全局命名空间中的 new/delete 时,我应该使用 std-rtl 中 new/delete 的什么默认实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6706966/