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;
    }
  • 相关阅读:
    中间件面试总结
    1.angular js 学习网址
    摄影构图
    mybatis学习(四)
    mybatis学习(三)
    mybatis学习(二)
    mybatis 学习(一)
    mysql 使用过程中出现问题
    springboot
    java 关键字
  • 原文地址:https://www.cnblogs.com/single-dont/p/11300311.html
Copyright © 2011-2022 走看看