本网站(662p.com)打包出售,且带程序代码数据,662p.com域名,程序内核采用TP框架开发,需要联系扣扣:2360248666 /wx:lianweikj
精品域名一口价出售:1y1m.com(350元) ,6b7b.com(400元) , 5k5j.com(380元) , yayj.com(1800元), jiongzhun.com(1000元) , niuzen.com(2800元) , zennei.com(5000元)
需要联系扣扣:2360248666 /wx:lianweikj
C++的new和delete使用示例详解
chenguangming9 · 146浏览 · 发布于2022-12-08 +关注

这篇文章主要为大家介绍了C++的new和delete使用示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

1. new 和 delete 

在C++中,动态的分配对象和释放对象我们使用的是new 和 delete那么,new 和 delete 与 c 语言中的 malloc 和 free有什么区别呢?

我们为什么又要使用new 和 delete 呢?

首先 在C++中,把 new 和 delete 改成了关键字;

new主要做三件事:调用operator new分配空间、初始化对象、返回指针。
这个时候,就体现出new 和 malloc 的区别来了,初始化对象,且返回的是一个该类的对象指针。

malloc 只是单纯的分配空间, 其他的事,一律不管。
若要用malloc体现出new的价值,大抵可以这样写一下(我自己的拙见)

template<typename T, typename ...PACK>
T *NEW(PACK... pack) {
  T *tmp = (T *) malloc(sizeof(T)); // 调用 malloc分配指针
  tmp->T::init(pack...); // 初始化对象
  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();

不够像的地方: 因为类调用不了自身的构造函数,构造函数的隐式调用的。 所有我采用了一个init函数来充当我的伪构造函数。(反正分配内存时也没调用构造函数嘛)

三种 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在已有的内存上构建,不重新分配内存

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);

对于第三种,很有意思,相当于把 分配内存和构造分开的设计

是不是有点眼熟?

啊对对对

就是alloctor的搞法嘛。

有时候构造操作是一个比较耗时的操作,这个时候就有用了

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 就是一个运算符了,且我们可以重载这个运算符,使其分配内存的方式是我们自定义的分配方式。

比如重载 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 有什么用啊? 有用?

当然,是有用的。在某些时候,可能重载分配方式可能是一个比较好的选择

众所周知,若是频繁的分配一些小对象又释放的,这样子的操作是不好的。

虽然操作系统可以帮我们干一些脏活累活,可是,若是根据性能瓶颈分析,发现问题出在分配小对象上面,这个时候我们就可以考虑整个内存池了。(内存分配策略是个大活,我这里的代码只是简单示例)

使用 内存池

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;

不使用内存池

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;

对比结果

在上述测试中, 使用内存池的时间稳定在 7.5 ms左右

不使用内存池稳定在 108 ms左右

当然,我这个测试是片面的,在这里,我只是想说明,重载 operator new 和 operator delete 的用途与好处

以上就是C++的new和delete使用示例详解的详细内容,


c++

相关推荐

PHP实现部分字符隐藏

沙雕mars · 1312浏览 · 2019-04-28 09:47:56
Java中ArrayList和LinkedList区别

kenrry1992 · 896浏览 · 2019-05-08 21:14:54
Tomcat 下载及安装配置

manongba · 957浏览 · 2019-05-13 21:03:56
JAVA变量介绍

manongba · 953浏览 · 2019-05-13 21:05:52
什么是SpringBoot

iamitnan · 1077浏览 · 2019-05-14 22:20:36
加载中

0评论

评论
分类专栏
小鸟云服务器
扫码进入手机网页