'new operator'和'operator new'之间的区别? [英] Difference between 'new operator' and 'operator new'?

查看:184
本文介绍了'new operator'和'operator new'之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

new operator和operator new之间有什么区别?

What is difference between "new operator" and "operator new"?

推荐答案

我通常尝试用不同的方式来区分两者,但在任何情况下都是一个很好的问题。

I usually try to phrase things differently to differentiate between the two a bit better, but it's a good question in any case.

运算符new是一个分配原始内存的函数 - 至少在概念上,它与没有太大区别malloc()。虽然这是很不寻常的,除非你写的东西像你自己的容器,你可以调用操作符new直接,如:

Operator new is a function that allocates raw memory -- at least conceptually, it's not much different from malloc(). Though it's fairly unusual unless you're writing something like your own container, you can call operator new directly, like:

char *x = static_cast<char *>(operator new(100));

也可以全局或特定类重载operator new。 IIRC,签名是:

It's also possible to overload operator new either globally, or for a specific class. IIRC, the signature is:

void *operator new(size_t);

当然,如果重载一个运算符new(全局或类)也想要/需要重载匹配运算符delete。对于什么是值得的,还有一个单独的运算符new []用于为数组分配内存 - 但是你几乎肯定更好地忽略整个混乱。

Of course, if you overload an operator new (either global or for a class), you'll also want/need to overload the matching operator delete as well. For what it's worth, there's also a separate operator new[] that's used to allocate memory for arrays -- but you're almost certainly better off ignoring that whole mess completely.

新运算符是通常用于从免费存储创建对象的

The new operator is what you normally use to create an object from the free store:

my_class *x = new my_class(0);

两者之间的区别是操作符新只是分配原始内存,没有其他的。新操作符通过使用operator new来分配内存,然后它调用适当类型的对象的构造函数,所以结果是在该内存中创建的一个真实的活对象。如果该对象包含任何其他对象(嵌入或作为基类),这些构造函数也被调用。

The difference between the two is that operator new just allocates raw memory, nothing else. The new operator starts by using operator new to allocate memory, but then it invokes the constructor for the right type of object, so the result is a real live object created in that memory. If that object contains any other objects (either embedded or as base classes) those constructors as invoked as well.

这篇关于'new operator'和'operator new'之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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