对C++中new的认识
生活随笔
收集整理的這篇文章主要介紹了
对C++中new的认识
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
在C++中,我們常會遇到三種new的形式:operator new 、new operator 、placement new
①new operator?(new操作符):①申請空間? ②創(chuàng)建對象
圖示步驟:
?
②operator new (操作符new): 申請空間
③placement new (定位new):對已申請的空間創(chuàng)建對象
格式:new(ptr)A("123")? ?ptr---指向一塊已經(jīng)申請好的空間
?
總結(jié):可以簡單的認(rèn)為②③是①操作的解刨。但在②③中,當(dāng)需要釋放空間時,需要顯式調(diào)用對象的析構(gòu)函數(shù)釋放類實體成員申請的空間。
?
代碼應(yīng)用:
#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 operatordelete str;String *str = new String[10];String *ps = (String *)operator new(sizeof(String)); //operator newnew(ps)String("Hello"); //placement newps->~String();operator delete(ps);return 0; }?
轉(zhuǎn)載于:https://www.cnblogs.com/single-dont/p/11300311.html
總結(jié)
以上是生活随笔為你收集整理的对C++中new的认识的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 排序算法之——选择排序
- 下一篇: C++ 预编译头文件