zoukankan      html  css  js  c++  java
  • 对C++中new的认识

    在C++中,我们常会遇到三种new的形式:operator new 、new operator 、placement new

    ①new operator (new操作符):①申请空间  ②创建对象

    图示步骤:

     

    ②operator new (操作符new): 申请空间

    ③placement new (定位new):对已申请的空间创建对象

    格式:new(ptr)A("123")   ptr---指向一块已经申请好的空间

    总结:可以简单的认为②③是①操作的解刨。但在②③中,当需要释放空间时,需要显式调用对象的析构函数释放类实体成员申请的空间。

    代码应用:

    #include<iostream>
    using namespace std;
    
    
    //operator new
    //new operator
    //placement new
    
    //重载new operator
    void* operator new(size_t sz)
    {
        void* p = malloc(sz);
        return p;
    }
    void operator delete(void *p)
    {
        free(p);
    }
    void operator delete[](void *p)
    {
        free(p);
    }
    
    class String;
    ostream& operator<<(ostream& out, String& str);
    
    class String
    {
    public:
        friend ostream& operator<<(ostream& out, String& str);
    public:
        String(const char* str = "")
        {
            std::cout<<"contruct Object"<<std::endl;
            if (str == NULL)
            {
                m_data = new char[1];
                m_data[0] = '';
            }
            else
            {
                m_data = new char[strlen(str) + 1];
                strcpy(m_data,str);
            }
        }
        ~String()
        {
            cout<<"free Object"<<endl;
            delete[]m_data;
            m_data = NULL;
        }
        
    private:
        char* m_data;
    };
    ostream& operator<<(ostream& out, String& str)
    {
        out << str.m_data;
        return out;
    }
    
    
    int main()
    {
        String *str = new String("Hello");// new operator
        delete str;
        String *str = new String[10];
        String *ps = (String *)operator new(sizeof(String)); //operator new
        new(ps)String("Hello");  //placement new
        ps->~String();
        operator delete(ps);
        return 0;
    }
  • 相关阅读:
    ubuntu下怎么配置/查看串口-minicom工具
    jpg与pgm(P5)的互相转换(Python)
    hyper-v安装ubuntu18的全过程+踩过的坑(win10家庭版)
    zerotier的下载、安装、配置与使用(win10、ubuntu)
    github page+jekyll构建博客的解决方案
    opencv2.4.13.7的resize函数使用(c++)
    c++中的const和volatile知识自我总结
    各种优化算法详解
    P与NP问题
    vs2017配置pthread.h的方法
  • 原文地址:https://www.cnblogs.com/single-dont/p/11300311.html
Copyright © 2011-2022 走看看