【问题标题】:How is `new (std::nothrow)` implemented?`new (std::nothrow)` 是如何实现的?
【发布时间】:2013-02-23 21:04:20
【问题描述】:

我有一个 C++ 程序,其中 new 运算符被重载。问题是 如果我在new 运算符中的分配失败,我仍在调用构造函数。 我知道我可以通过抛出 std::bad_alloc 来避免这种情况,但我不想这样做。

我如何在重载的new 运算符中失败并且仍然不调用我的构造函数? 本质上我想实现类似new (std::nothrow)

这里有一个例子来说明我的意思。 请注意,我正在测试的系统 on 没有内存保护。所以访问NULL 没有任何作用

示例 1:重载 new 运算符

#include <stdio.h>
#include <stdlib.h>
#include <memory>

class Test {

public:

    Test(void) {
        printf("Test constructor\n");
    }

    void print(void) {
        printf("this: %p\n", this);
    }

    void* operator new(size_t size, unsigned int extra) {

        void* ptr = malloc(size + extra);
        ptr = NULL; // For testing purposes
        if (ptr == NULL) {
            // ?
        }
        return ptr;
    }
};

int main(void) {

    Test* t = new (1) Test;            
    t->print();
    printf("t: %p\n", t);

    return 0;
}

这个的输出是:

$ ./a.out
Test constructor
this: 00000000
t: 00000000

显然,当new 失败时,构造函数被调用

示例 2:带有 new (std::nothrow) 的巨大类声明

#include <stdio.h>
#include <stdlib.h>
#include <memory>

class Test {

    int x0[0x0fffffff];
    int x1[0x0fffffff];
    int x2[0x0fffffff];
    int x3[0x0fffffff];
    int x4[0x0fffffff];
    int x5[0x0fffffff];
    int x6[0x0fffffff];
    int x7[0x0fffffff];
    int x8[0x0fffffff];
    int x9[0x0fffffff];
    int xa[0x0fffffff];
    int xb[0x0fffffff];
    int xc[0x0fffffff];
    int xd[0x0fffffff];
    int xe[0x0fffffff];
    int xf[0x0fffffff];

public:

    Test(void) {
        printf("Test constructor\n");
    }

    void print(void) {
        printf("this: %p\n", this);
    }
};

int main(void) {

    Test* t = new (std::nothrow) Test;    
    t->print();
    printf("t: %p\n", t);

    return 0;
}

这个的输出是:

this: 00000000
t: 00000000    

显然,当new 失败时,构造函数没有被调用

那么我如何在我的 重载new 运算符?

【问题讨论】:

    标签: c++ memory-management new-operator


    【解决方案1】:

    编译器在调用后是否检查空指针 operator new 与否,在调用析构函数之前,取决于 分配器函数是否有非抛出异常 规范与否。如果不是,编译器假定 如果没有可用内存,operator new 将抛出。否则, 它假定operator new 将返回一个空指针。在 你的情况,你的operator new应该是:

    void* operator new( size_t size, unsigned int extra ) throw()
    {
        //...
    }
    

    或者如果您可以依靠 C++11 支持:

    void* operator new( size_t size, unsigned int extra) noexcept
    {
    }
    

    【讨论】:

    • 非常感谢,我永远猜不到答案。只是一个问题,不管你说什么,它是否记录在 C++2003 标准的任何地方?
    • §5.3.4/13:“如果分配函数返回 null,则不应进行初始化,不应调用释放函数,并且 new-expression 的值应为 null。”
    • 实际上,在 C++11 和 C++03 中,行为都在 [basic.stc.dynamic.allocation]/3 中指定。对于 C++11,措辞是:“如果使用非抛出异常规范声明的分配函数未能分配存储,它应返回一个空指针。任何其他未能分配存储的分配函数应仅通过以下方式指示失败抛出与 std::bad_alloc 类型的处理程序匹配的类型的异常。” C++03 的措辞非常相似。
    猜你喜欢
    • 2014-04-26
    • 1970-01-01
    • 2015-01-14
    • 2013-11-01
    • 2020-04-26
    • 2010-11-30
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多