替换函数“operator new”不能声明为“内联”[-Werror,-Winline-new-delete]

win*_*der 5 c++ inline clang new-operator

我在使用 clang 时遇到此错误。为什么operator new不能声明为内联?

./test.h:198:1: error: replacement function 'operator new' cannot be declared 'inline' [-Werror,-Winline-new-delete]
__forceinline void *operator new(size_t size) { return malloc(size); }
^
./test.h:18:23: note: expanded from macro '__forceinline'
#define __forceinline inline __attribute__((__always_inline__))

                  ^
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 4

整个程序中分配函数的所有使用都必须兼容。在一个翻译单元中分配的某些内容operator new必须可以operator delete在另一个翻译单元中取消分配。因此,程序必须在各处得到相同的实现,并且分配函数的替换不是TU本地的事情,而是全局的选择。

因此,与其要求每个 TU 都包含相同的代码(这将违背静默、非侵入性替换的目的,并且违反该目的将极难诊断),而是要求该函数具有外部链接而不是内联。

将分配函数视为程序全局状态的一部分。