gpt4 book ai didi

c++ - 为什么新运算符不声明为 [[nodiscard]]?

转载 作者:太空宇宙 更新时间:2023-11-04 12:55:48 24 4
gpt4 key购买 nike

C++17 在 p0189r1 中引入了新属性 [[nodiscard]] .当一个函数被这个属性修饰时,返回类型不能被丢弃。如果它被丢弃,则会发出警告。

例子:

[[nodiscard]] void* allocateMemory();

void doWork() {
allocateMemory(); // Warning is emitted, because the value is not stored in a variable and thus is discarded
}

对于返回任何稍后必须再次释放/销毁/删除/...的任何函数,这似乎是一个很好的补充。但是,该标准并未更改全局新运算符的定义以使用此新注释。这有什么好的理由吗?

最佳答案

论文P0600R0提议将 [[nodiscard]] 应用于库函数,并将全局 operator new 枚举为必须应用的函数之一。
正如 TC 在评论中提到的那样,这无法使其符合 C++17 标准本身。标题为:"[[nodiscard]] in the Library" 的错误也被提起。决定将其采纳到以后的草案中。

标准草案 n4713 包含此更改。

6.6.4.4 Dynamic storage duration [basic.stc.dynamic]
...
2. ... The following allocation and deallocation functions are implicitly declared in global scope in each translation unit of a program.

[[nodiscard]] void* operator new(std::size_t);
[[nodiscard]] void* operator new(std::size_t, std::align_val_t);

关于c++ - 为什么新运算符不声明为 [[nodiscard]]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46751006/

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