gpt4 book ai didi

c++ - 重载 operator new 和异常正确性

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:48:33 25 4
gpt4 key购买 nike

在查看遗留代码时,我发现了类似于以下代码的内容

void* legacy_type::operator new(size_t size) {
return pool_alloc(size);
}

众所周知,pool_alloc 在失败的情况下永远不会抛出并返回 0。

这里没有 std::nothrow 的 new 变体的重载。

我想知道这段代码在语义上是否正确并且是否具有明确定义的行为。

new (std::nothrow) legacy_type; 是否应该使用自定义 pool_alloc?在我的编译器中它根本不编译。它是明确定义的行为吗?

如果重载 operator new 返回零,构造函数是否应该运行并由于 this==0 而崩溃?在我的编译器中它运行(并在成员初始化时崩溃)。它是标准的定义明确的行为吗?

最佳答案

1) 不,不应该。这些是不同的功能。而且,当您重载其中一个操作时 - 所有其他操作将永远不会工作,如果它们没有被重载,因为如果类范围内有 operator new 并且签名是 Not Acceptable ,那么编译器将不会搜索 global operator new,因此,会发生编译错误。

2) 如果你的 new 将返回空指针,你就打破了后置条件。n3376 18.6.1.1/3

Required behavior: Return a non-null pointer to suitably aligned storage (3.7.4), or else throw a bad_-alloc exception. This requirement is binding on a replacement version of this function.

如果你想返回0,你应该使用下面的签名

void* operator new(size_t) throw()

如果您使用此重载并从中返回 0,则没有段错误。

n3376 5.3.4/13

If theallocation function returns null, initialization shall not be done, the deallocation function shall not be called,and the value of the new-expression shall be null.

关于c++ - 重载 operator new 和异常正确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19706868/

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