對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] = '\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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM