zoukankan      html  css  js  c++  java
  • operator new 与 placement 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;
    }
    
    
  • 相关阅读:
    实现Android-JNI本地C++调试
    OpenCV中IplImage/CvMat/Mat转化关系
    安卓项目中文件夹的作用
    SLAM: 图像角点检测的Fast算法(OpenCV文档)
    CVPR2015深度学习回顾
    ANN:DNN结构演进History—LSTM网络
    ANN:DNN结构演进History—RNN
    最优化:**回归/拟合方法总结
    Matlab中数组元素引用——三种方法
    C++ Rand()各种实现
  • 原文地址:https://www.cnblogs.com/laohaozi/p/12537742.html
Copyright © 2011-2022 走看看