c++ - 在 C++ 全局运算符上 new : why it can be replaced

标签 c++

我在VS2005中写了一个小程序测试C++全局operator new是否可以重载。可以。

#include "stdafx.h"
#include "iostream"
#include "iomanip"
#include "string"
#include "new"

using namespace std;

class C {
    public:
        C() { cout<<"CTOR"<<endl; }
};

void * operator new(size_t size) 
{
    cout<<"my overload of global plain old new"<<endl;
    // try to allocate size bytes
    void *p = malloc(size);
    return (p);
}

int main() {
    C* pc1 = new C;
    cin.get();
    return 0;
}

上面调用了我定义的operator new。如果我从代码中删除该函数,则会调用 C:\Program Files (x86)\Microsoft Visual Studio 8\VC\crt\src\new.cpp 中的 operator new。

一切都很好。但是,在我看来,我对 operator new 的实现不会在 new.cpp 中重载 new,它会与之冲突并违反单一定义规则。为什么编译器不提示它?还是标准说因为 operator new 非常特殊,所以这里不适用单一定义规则?

谢谢。

最佳答案

是的,global operator new 的特殊之处在于程序可能会为其提供替代实现。

可替换形式是 operator newoperator delete 的单个对象和数组形式以及“不抛出”变体。其他形式,如 placement new 是不可替换的。

关于c++ - 在 C++ 全局运算符上 new : why it can be replaced,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2728944/

相关文章:

c++ - 顶点在 Frustum 外的 OpenGL 透视投影裁剪多边形 = 错误的纹理映射?

c# - 调试底层 C++ DLL 中的问题

c++ - 编译着色器时出错 - DirectX11

c++ - bool返回值的函数,只设置整个寄存器的1个字节

c++ - 将 UTC 中的 QDateTime 转换为本地系统时间

c++ - 如何在没有选择的情况下更改 QTextEdit 中的当前行格式?

c++ - 绘制带渐变的圆有问题

c++ - 按值传递认为参数是const

c++ - 在 C++ 中调用静态链接的静态方法

c++ - 亚洲 : best way to store a message to be broadcast