当分配返回0时,运算符new具有空异常规范调用构造函数 [英] operator new with empty exception-specification calling constructor when allocation returns 0

查看:168
本文介绍了当分配返回0时,运算符new具有空异常规范调用构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下声明:

void * operator new (size_t s, PersistentMemory * m) throw()
   {return m->allocatePersistentMemory(s);}

启动,这导致 m-> allocatePersistentMemory(s); 返回0.新的然后调用具有空指针的构造函数 / code>

I'm testing memory exhaustion on start-up, which results in m->allocatePersistentMemory(s); returning 0. New then calls the constructor with a null pointer for this

但是,基于C ++ 2003标准的3.7.3.1第3段:

However, based on 3.7.3.1 paragraph 3 of C++ 2003 standard:


无法分配存储的分配函数可以调用当前安装的
new_handler(18.4.2.2)(如果有)。 [注:A
程序提供的分配函数可以使用set_new_handler函数
(18.4.2.3)获取当前安装的new_handler
的地址。 ]如果一个声明为空的
异常规范(15.4)throw()的分配函数无法分配存储,那么
将返回一个空指针。任何其他失败
分配存储的分配函数只能通过抛出std :: bad_alloc(18.4.2.1)类的
异常或从
std :: bad_alloc派生的类来指示失败。

An allocation function that fails to allocate storage can invoke the currently installed new_handler (18.4.2.2), if any. [Note: A program-supplied allocation function can obtain the address of the currently installed new_handler using the set_new_handler function (18.4.2.3). ] If an allocation function declared with an empty exception-specification (15.4), throw(), fails to allocate storage, it shall return a null pointer. Any other allocation function that fails to allocate storage shall only indicate failure by throwing an exception of class std::bad_alloc (18.4.2.1) or a class derived from std::bad_alloc.

我理解的方式是具有 m-> allocatePersistentMemory return null应该会导致整个运算符new()throw()返回null而不调用构造函数。

The way I understand things is that having m->allocatePersistentMemory(s) return null should result in the whole operator new() throw() returning null without calling the constructor. Am I missing some other condition elsewhere that overrides this?

推荐答案

我怀疑你没有拨打 new http://ideone.com/Go3G3rel =nofollow>这符合您的预期。

This works as you expect.

void *myalloc (size_t) { return 0; }
void * operator new (size_t s) throw() { return myalloc(s); }
struct Foo {
    std::string s;
    Foo () { std::cout << this << std::endl; }
};
int main () {
    Foo *f = new Foo;
    if (f == 0) std::cout << "f is NULL" << std::endl;
}

其中这会失败。

void *myalloc (size_t) { return 0; }
void * operator new (size_t s) throw() { return myalloc(s); }
struct Foo {
    std::string s;
    Foo () { std::cout << this << std::endl; }
    void * operator new (size_t s) { return myalloc(s); }
};
int main () {
    Foo *f = new Foo;
    if (f == 0) std::cout << "f is NULL" << std::endl;
}

这篇关于当分配返回0时,运算符new具有空异常规范调用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆