operator new 与 placement new之间的微妙关系

本文详细介绍了在C++中如何自定义new运算符,包括不同形式的new运算符重载,以及它们在内存分配过程中的作用。通过具体代码示例,展示了自定义new运算符的具体实现和使用场景。
#include <iostream>
#include <cstdlib>
using namespace std;

class Base{
  public:
        Base(int n):_A(n){
            _A = n;
        }
        Base(){
            _A = -1;
        }
        // 注意: 一旦有一个operator new 重载,那么其他的operator new 形式的函数都必须重载
        
        // 第一个参数 size_t size, 为固定参数类型,传入需要内存的大小
        static void* operator new(size_t size, void* p, int n){
            cout<< "size:"<<size<<endl;
            cout<< "n:"<<n<<endl;
            return p;
        }
        
        // 这个是new(p)Base;  new(p)Base(20);的处理函数,如果不重载,那么
        // 当调用上面两个初始化方法时,就会报出错误
        // 它也什么也没有做,应该也是编绎器自带的operator new的实现方法
        // 有人把这种调用称为placement new,其实我觉的它们都一样吧,hhhh
        static void* operator new(size_t size, void *p){
            cout<<" static void* operator new(size_t size, void *p)- >"<<size<<endl;
            return p;
        }
        
        // 这个更离奇,如果不重载,那没法调用 new Base; new Base(20);
        // emmm,其他它什么也没有做,它应该就是编译器自带的operator new的实现方式
        static void* operator new(size_t size){
            cout<<"static void* operator new(size_t size)->"<<size<<endl;
            return malloc(size);
        }
        
    void show(){
        cout<<"_A:"<<_A<<endl;
    }
  private:
        int _A;
        int b;
        
};
int main(){
    Base* p2 = nullptr;
    // 如果malloc分配的空间小,可能也不会出错,但是会把内存空间给挤过去
    Base* p= (Base*)malloc(sizeof(Base));
    cout<<"sizeof(Base)->"<<sizeof(Base)<<endl;
    cout<<"p->"<<p<<endl;
    new(p)Base(20);
    p->show();
    cout<<"-------------"<<endl;
    p2 = new Base(100);
    p2->show();
    cout<<"p->"<<p<<endl;
    cout<<"p2->"<<p2<<endl;
    cout<<"-------------"<<endl;
    Base obj(2);
    obj.show();
    new(&obj)Base(20);
    obj.show();
    return 0;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值