为什么要显式调用运算符new [英] why call operator new explicitly

查看:112
本文介绍了为什么要显式调用运算符new的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了这样的代码:

void *NewElts = operator new(NewCapacityInBytes);

随后将使用显式匹配呼叫operator delete.

And matching call explicitly operator delete is used consequent later.

为什么要这样做,而不是:

Why do this instead of:

void *NewElts = new char[NewCapacityInBytes];

为什么要显式调用operator newoperator delete ??

Why explicit call to operator new and operator delete??

推荐答案

像这样显式调用operator new会将全局原始"运算符称为new.全局operator new返回原始内存块,而不调用对象的构造函数或用户定义的new重载.因此,基本上,全局operator new与C中的malloc相似.

Explicitly calling operator new like that calls the global "raw" operator new. Global operator new returns a raw memory block without calling the object's constructor or any user-defined overloads of new. So basically, global operator new is similar to malloc from C.

所以:

// Allocates space for a T, and calls T's constructor,
// or calls a user-defined overload of new.
//
T* v = new T;

// Allocates space for N instances of T, and calls T's 
// constructor on each, or calls a user-defined overload
// of new[]
//
T* v = new T[N];

// Simply returns a raw byte array of `sizeof(T)` bytes.
// No constructor is invoked.
//
void* v = ::operator new(sizeof(T));

这篇关于为什么要显式调用运算符new的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆