gpt4 book ai didi

c++ - 当分配返回 0 时,带有空异常规范调用构造函数的 operator new

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:55:54 26 4
gpt4 key购买 nike

我有以下声明:

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

我正在测试启动时的内存耗尽,这会导致 m->allocatePersistentMemory(s); 返回 0。New 然后使用空指针为 this< 调用构造函数

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

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(s) 返回 null 应该导致整个 operator new() throw() 返回 null 而无需调用构造函数。我是否遗漏了其他覆盖此条件的其他条件?

谢谢!

最佳答案

我怀疑您没有调用您认为正在调用的 new

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;
}

哪里,this fails.

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;
}

关于c++ - 当分配返回 0 时,带有空异常规范调用构造函数的 operator new,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11514185/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com