c++ - 在覆盖全局命名空间中的 new/delete 时,我应该使用 std-rtl 中 new/delete 的什么默认实现?

标签 c++ std new-operator overriding

我将 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/

相关文章:

c++ - 下面的内存分配有用吗?

c++ - 为什么在 Linux 上使用更多线程时内存消耗会增加? (C++)

c++ - __PRETTY_FUNCTION__、__FUNCTION__、__func__ 有什么区别?

c++ - 尝试在 C++ SFML 代码块中设置帧率时出错

c++ - Visual Studios 能否用于在 C++ 中进行开发并仍然创建能够在 Mac 上运行的程序?

c++ - std::cin 在不应该接收输入时接收输入

c++ - Visual C++ 2010 拒绝在调试时显示 std::string 值。显示 <Bad Ptr>

c++ - 检索C++ vector 中的第一个元素

c++ - 如何正确调用对齐的新/删除?

c++ - 如何区分 POD 和用户定义的数据类型?