日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

对C++中new的认识

發(fā)布時間:2024/1/17 c/c++ 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 对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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。