zoukankan      html  css  js  c++  java
  • operator new和operator delete

    从STL源码剖析中看到了operator new的使用

    template<class T>
    inline void _deallocate(T* buffer) {
        ::operator delete(buffer);
        //operator delete可以被重载
    //    operator delete(buffer);
    }
    

     从而开始研究一下这两个操作符

    首先其实迷惑的是"::"的作用,通过以下代码测试出来了

    class A {
    public:
    	void TT() {
    		cout << "A" << endl;
    	}
    };
    inline void TT() {
    	cout<<"G"<<endl;
    }
    class B: public A {
    public:
    	void TT() {
    		cout << "B" << endl;
    		::TT();
    	}
    };
    
    int main(int argc, char **argv) {
    //	new Allocator();
    	(new B())->TT();
    	return 0;
    }
    

     运行结果

    B
    G
    

     用于区分全局函数和函数内局部函数的符号。

    #include <iostream>
    #include <vector>
    #include "2jjalloca.h"
    #include <new>

    using namespace std;

    //inline void *operator new(size_t n) {
    //    cout << "global new" << endl;
    //    return ::operator new(n);
    //}
    //
    //inline void *operator new(size_t n, const std::nothrow_t& nt) {
    //    cout << "global new nothrow" << endl;
    //    return ::operator new(n, nt);
    //}

    class Allocator {
    public:
        void *operator new(size_t n) {
            cout << "allocator new" << endl;
            return ::operator new(n);
        }
        //作用域覆盖原则,即在里向外寻找operator new的重载时,
        //只要找到operator new()函数就不再向外查找,如果参数符合则通过,
        //如果参数不符合则报错,而不管全局是否还有相匹配的函数原型。
        //所以的调用new(std::nothrow) Allocator;注释这个函数是报错
        void* operator new(size_t n, const std::nothrow_t& nt) {
            cout << "allocator new nothrow" << endl;
            return ::operator new(n, nt);
        }

        void* operator new(size_t n, void *p) {
            cout << "allocator placement new" << endl;
            return p;
        }

        void operator delete(void *p) {
            cout << "allocator delete" << endl;
            return ::operator delete(p);
        }
        void operator delete(void*, void*) {
            cout << "allocator placement delete" << endl;
        }

        void* operator new[](size_t n) {
            cout << "allocator new[]" << endl;
            return ::operator new[](n);
        }
    };

    int main(int argc, char **argv) {
    //    Allocator *a = new Allocator;
    //    delete a;
    //    ::new Allcator;

        Allocator *a=new Allocator[10];
        return 0;
    }


     参考文章

    C++ 内存分配(new,operator new)详解 (有些和我尝试的不一样,第四节可以着重参考)

    少壮不识cpp,老大方知cpp可怕
  • 相关阅读:
    seaborn基础整理
    matplotlib基础整理
    pandas基础整理
    numpy基础整理
    二分算法的应用——不只是查找值!
    二分算法的应用——Codevs 1766 装果子
    数据挖掘实战(二)—— 类不平衡问题_信用卡欺诈检测
    数论:素数判定
    MySQL学习(二)——MySQL多表
    MySQL学习(一)——Java连接MySql数据库
  • 原文地址:https://www.cnblogs.com/Jacket-K/p/9337131.html
Copyright © 2011-2022 走看看