替换 "operator new" 时出现警告 (C28251):'new' 的注释不一致,此实例没有注释

Warning (C28251) when replacing "operator new": Inconsistent annotation for 'new', this instance has no annotations

我正在尝试替换 Visual Studio 和 C++ 中的全局 new 运算符。这是我的代码(为简单起见只显示了一个新运算符):

void* operator new(size_t _Size)
{
    // Do something
}

它工作正常,但是 Visual Studio 在对我的项目进行 运行 代码分析时给我一个警告:

warning C28251: Inconsistent annotation for 'new': this instance has no annotations. The first user-provided annotation on this built-in function is at line vcruntime_new.h(48).

按照 IntelliSense 警告中的建议,使用 vcruntime_new.h 中的注释替换我的 operator new,解决了警告:

_NODISCARD _Ret_notnull_ _Post_writable_byte_size_(_Size) _VCRT_ALLOCATOR
void* __cdecl operator new(size_t _Size)
{
    // Do something
}
  1. 将 vcruntime_new.h 中的注释用于我自己的如上所示的替换代码是否安全?
  2. 此更改的后果是什么?
  3. 是否有特殊用例,因为注释不能再像以前那样使用“新运算符”?
  4. 为什么需要进行这种更改?

编辑:

  1. 我是否正确,注释不会更改生成的二进制文件中的任何内容,并且仅用于静态代码分析? (除了 __cdecl,它改变了汇编器,但我猜它应该是标准的吧?)

这适用于 _Ret_notnull__Post_writable_byte_size_(_Size):

Is it safe to use the annotations inside vcruntime_new.h for my own replacement code like shown above?

可以,只要您的操作员 new 在注释中实际遵循这些规则。它可能不会遵循 _Ret_notnull_(例如非抛出 new returns nullptr),通常会。但它应该跟在 _Post_writable_byte_size_(_Size) 之后,因为 operator new 是必需的。

What are the consequences of this change?

注释可能有助于 Visual Studio 代码分析查明错误,但会使您使用非标准的东西,使您的程序的可移植性和清晰度降低。

Are there special use cases were the "new operator" cannot be used anymore like before because of the annotations?

没有

And why is that change necessary?

因为您想避免该警告而不是将其静音。

Am I correct, that the annotations won't change anything in the resulting binary, and are simply for static code analysis? (Except __cdecl, which changes the assembler, but it should be standard anyway I guess?)

正确。甚至优化器也不会使用它(优化器会使用 __assume__restrict 和其他与静态分析分开的注释)。