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

1. new 和 delete 

C++中,动态的分配对象和释放对象我们使用的是newdelete那么,newdeletec 语言中的 mallocfree有什么区别呢?

我们为什么又要使用newdelete 呢?

首先 在C++中,把 newdelete 改成了关键字;

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

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 newoperator delete 的用途与好处

作者:amjieker

%s 个评论

要回复文章请先登录注册