亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

C++的new和delete使用示例詳解

 更新時(shí)間:2022年12月07日 15:38:58   作者:amjieker  
這篇文章主要為大家介紹了C++的new和delete使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

1. new 和 delete 

C++中,動(dòng)態(tài)的分配對(duì)象和釋放對(duì)象我們使用的是newdelete那么,newdeletec 語言中的 mallocfree有什么區(qū)別呢?

我們?yōu)槭裁从忠褂?code>new 和 delete 呢?

首先 在C++中,把 newdelete 改成了關(guān)鍵字;

new主要做三件事:調(diào)用operator new分配空間、初始化對(duì)象、返回指針。
這個(gè)時(shí)候,就體現(xiàn)出newmalloc 的區(qū)別來了,初始化對(duì)象,且返回的是一個(gè)該類的對(duì)象指針。

malloc 只是單純的分配空間, 其他的事,一律不管。
若要用malloc體現(xiàn)出new的價(jià)值,大抵可以這樣寫一下(我自己的拙見)

template<typename T, typename ...PACK>
T *NEW(PACK... pack) {
  T *tmp = (T *) malloc(sizeof(T)); // 調(diào)用 malloc分配指針
  tmp->T::init(pack...); // 初始化對(duì)象
  return tmp; // 返回指針
}

示例類

struct E {
  int x, y;
  void init() {this->x = 0;this->y = 0;}
  void init(int x) {
    init();
    this->x = x;
  }
  void init(int x, int y) {
    init();
    this->x = x;this->y = y;
  }
  void print() {cout << x << " " << y << endl;}
  void add(const E &rsh) {
    this->x += rsh.x;
    this->y += rsh.y;
  }
};

使用

auto tmp1 = NEW<E>(1);
auto tmp2 = NEW<E>(1, 2);
tmp1->print();
tmp2->print();

不夠像的地方: 因?yàn)轭愓{(diào)用不了自身的構(gòu)造函數(shù),構(gòu)造函數(shù)的隱式調(diào)用的。 所有我采用了一個(gè)init函數(shù)來充當(dāng)我的偽構(gòu)造函數(shù)。(反正分配內(nèi)存時(shí)也沒調(diào)用構(gòu)造函數(shù)嘛)

三種 new

拋異常的 new

void *operator new(std::size_t count)
throw(std::bad_alloc);
try {
  const long long N = 10e18;
  auto p = new int8_t[N];
  delete p;
} catch (std::bad_alloc &bad) {
  cout << bad.what() << endl;
}

不拋異常的 new

void *operator new(std::size_t count,
   const std::nothrow_t&) throw();
long long N = 10e18;
auto p = new(std::nothrow) int8_t[N];
assert(p);

palcement new在已有的內(nèi)存上構(gòu)建,不重新分配內(nèi)存

struct E {
  int x, y;
};
auto mall = ::malloc(100);
auto p = new(mall) E{.x = 1, .y = 2};
int32_t *now = static_cast<int32_t *>(mall);
cout << *now << endl;
cout << *++now << endl;
free(mall);

對(duì)于第三種,很有意思,相當(dāng)于把 分配內(nèi)存和構(gòu)造分開的設(shè)計(jì)

是不是有點(diǎn)眼熟?

啊對(duì)對(duì)對(duì)

就是alloctor的搞法嘛。

有時(shí)候構(gòu)造操作是一個(gè)比較耗時(shí)的操作,這個(gè)時(shí)候就有用了

struct E {
  int x, y;
  E(int x = 0, int y = 0) : x(x), y(y) {}
  void print() { cout << x << " " << y << endl; }
  void add(const E &rsh) {
    this->x += rsh.x;
    this->y += rsh.y;
  }
};
template<typename T>
T *allocate() { return static_cast<T *>(::malloc(sizeof(T))); }
template<typename T, typename ...PACK>
T *construct(void *ptr, PACK... pack) {
  return new(ptr) T(pack...);
}
signed main() {
  auto t = allocate<E>();
  t = construct<E>(t, 1, 2);
  t->print();
  return 0;
}

2. operator new 和 operator delete

operator new 就是一個(gè)運(yùn)算符了,且我們可以重載這個(gè)運(yùn)算符,使其分配內(nèi)存的方式是我們自定義的分配方式。

比如重載 operator new 來給 new

struct E {
  E() { cout << "construct" << endl; }
  void *operator new(std::size_t length) {
    cout << "malloc object" << endl;
    return ::malloc(length);
  }
  void *operator new[](std::size_t length) {
    cout << "malloc array" << endl;
    return ::malloc(length);
  }
  void operator delete(void *now) {
    cout << "free object" << endl;
    ::free(now);
  }
  void operator delete[](void *now) {
    cout << "free array" << endl;
    ::free(now);
  }
};
signed main() {
  auto t = new E;
  auto tarray = new E[2];
  delete t;
  delete[] tarray;
}
/* output
malloc object
construct
malloc array
construct
construct
free object
free array
*/

3. 重載 operator new 和 operator delete 有什么用?。?有用?

當(dāng)然,是有用的。在某些時(shí)候,可能重載分配方式可能是一個(gè)比較好的選擇

眾所周知,若是頻繁的分配一些小對(duì)象又釋放的,這樣子的操作是不好的。

雖然操作系統(tǒng)可以幫我們干一些臟活累活,可是,若是根據(jù)性能瓶頸分析,發(fā)現(xiàn)問題出在分配小對(duì)象上面,這個(gè)時(shí)候我們就可以考慮整個(gè)內(nèi)存池了。(內(nèi)存分配策略是個(gè)大活,我這里的代碼只是簡(jiǎn)單示例)

使用 內(nèi)存池

struct E {
  int arr[100];
  void *operator new(std::size_t size);
  void operator delete(void *ptr);
};
struct ENode {
  void *node;
  ENode *next;
};
const int MAX_LENGTH = 1024;
ENode *poll = nullptr, *use = nullptr;
auto init = []() -> bool {
  auto now = poll;
  for (int i = 0; i < MAX_LENGTH; i++) {
    if (i == 0) poll = now = new ENode{.node = malloc(sizeof(E)), .next = nullptr};
    else {
      auto pre = now;
      now = new ENode{.node = malloc(sizeof(E)), .next = nullptr};
      pre->next = now;
    }
  }
  return true;
}();
void *E::operator new(std::size_t size) {
  assert(poll != nullptr);
  auto now = poll;
  poll = poll->next;
  now->next = use;
  use = now;
  return now->node;
}
void E::operator delete(void *ptr) {
  assert(use != nullptr);
  auto now = use;
  use = use->next;
  now->next = poll;
  poll = now;
  poll->node = ptr;
}
auto t = std::chrono::high_resolution_clock::now();
E *arr[1024];
for (int i = 0; i < 1000; i++) {
  for (int j = 0; j < 1024; j++) {
    arr[j] = new E;
  }
  for (int j = 0; j < 1024; j++) {
    delete arr[(j + i) % 1024];
  }
}
cout << (std::chrono::high_resolution_clock::now() - t).count() << endl;

不使用內(nèi)存池

struct W {
  int arr[100];
};
auto t = std::chrono::high_resolution_clock::now();
W *arr[1024];
for (int i = 0; i < 1000; i++) {
  for (int j = 0; j < 1024; j++) {
    arr[j] = new W;
  }
  for (int j = 0; j < 1024; j++) {
    delete arr[(j + i) % 1024];
  }
}
cout << (std::chrono::high_resolution_clock::now() - t).count() << endl;

對(duì)比結(jié)果

在上述測(cè)試中, 使用內(nèi)存池的時(shí)間穩(wěn)定在 7.5 ms左右

不使用內(nèi)存池穩(wěn)定在 108 ms左右

當(dāng)然,我這個(gè)測(cè)試是片面的,在這里,我只是想說明,重載 operator newoperator delete 的用途與好處

以上就是C++的new和delete使用示例詳解的詳細(xì)內(nèi)容,更多關(guān)于C++ new和delete使用的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 詳細(xì)解析命令行的getopt_long()函數(shù)

    詳細(xì)解析命令行的getopt_long()函數(shù)

    getopt_long支持長(zhǎng)選項(xiàng)的命令行解析,函數(shù)中的參數(shù)argc和argv通常直接從main()的兩個(gè)參數(shù)傳遞而來
    2013-09-09
  • VSCode Linux的C++代碼格式化配置的實(shí)現(xiàn)

    VSCode Linux的C++代碼格式化配置的實(shí)現(xiàn)

    動(dòng)格式化代碼容易出現(xiàn)錯(cuò)誤,特別是當(dāng)代碼量較大時(shí),使用自動(dòng)格式化可以減少這種錯(cuò)誤的風(fēng)險(xiǎn),本文主要介紹了VSCode Linux的C++代碼格式化配置的實(shí)現(xiàn),感興趣的可以了解一下
    2023-10-10
  • C++標(biāo)準(zhǔn)庫學(xué)習(xí)之weak_ptr智能指針用法詳解

    C++標(biāo)準(zhǔn)庫學(xué)習(xí)之weak_ptr智能指針用法詳解

    這篇文章主要為大家詳細(xì)介紹了C++標(biāo)準(zhǔn)庫中weak_ptr智能指針用法的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-12-12
  • C語言進(jìn)階練習(xí)二叉樹的遞歸遍歷

    C語言進(jìn)階練習(xí)二叉樹的遞歸遍歷

    樹是一種重要的非線性數(shù)據(jù)結(jié)構(gòu),直觀地看,它是數(shù)據(jù)元素(在樹中稱為結(jié)點(diǎn))按分支關(guān)系組織起來的結(jié)構(gòu),很象自然界中的樹那樣。樹結(jié)構(gòu)在客觀世界中廣泛存在,如人類社會(huì)的族譜和各種社會(huì)組織機(jī)構(gòu)都可用樹形象表示,本篇介紹二叉樹的遞歸與非遞歸遍歷的方法
    2022-06-06
  • C++ opencv ffmpeg圖片序列化實(shí)現(xiàn)代碼解析

    C++ opencv ffmpeg圖片序列化實(shí)現(xiàn)代碼解析

    這篇文章主要介紹了C++ opencv ffmpeg圖片序列化實(shí)現(xiàn)代碼解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-08-08
  • C++詳細(xì)分析引用的使用及其底層原理

    C++詳細(xì)分析引用的使用及其底層原理

    引用是C++一個(gè)很重要的特性,顧名思義是某一個(gè)變量或?qū)ο蟮膭e名,對(duì)引用的操作與對(duì)其所綁定的變量或?qū)ο蟮牟僮魍耆葍r(jià),這篇文章主要給大家總結(jié)介紹了C++中引用的相關(guān)知識(shí)點(diǎn),需要的朋友可以參考下
    2022-04-04
  • C++內(nèi)存查找實(shí)例

    C++內(nèi)存查找實(shí)例

    這篇文章主要介紹了C++內(nèi)存查找實(shí)例,可實(shí)現(xiàn)Windows程序設(shè)計(jì)中的內(nèi)存查找功能,需要的朋友可以參考下
    2014-10-10
  • 基于Matlab實(shí)現(xiàn)繪制3D足球的示例代碼

    基于Matlab實(shí)現(xiàn)繪制3D足球的示例代碼

    這篇文章主要為大家詳細(xì)介紹了如何利用Matlab實(shí)現(xiàn)繪制3D足球,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Matlab有一定幫助,需要的可以參考一下
    2022-11-11
  • C語言利用sprintf固定字符串輸出位數(shù)

    C語言利用sprintf固定字符串輸出位數(shù)

    sprintf?函數(shù)是一個(gè)?C?語言中的函數(shù),也被許多其他編程語言所支持。這篇文章主要介紹了C語言如何利用sprintf固定字符串輸出位數(shù),需要的可以參考一下
    2023-03-03
  • C++中const與#define的利弊分析

    C++中const與#define的利弊分析

    C++中不但可以用define定義常量還可以用const定義常量,下面這篇文章主要給大家分析介紹了關(guān)于C++中const與#define的利弊,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2018-05-05

最新評(píng)論