对C++中new的认识

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

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

图示步骤:

 对C++中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;
}

 

原文链接: https://www.cnblogs.com/single-dont/p/11300311.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    对C++中new的认识

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/300516

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 下午9:30
下一篇 2023年2月15日 下午9:30

相关推荐