为什么c ++对于new&删除? [英] Why does c++ have its separate syntax for new & delete?
问题描述
malloc(sizeof(Foo));
Foo :: Foo();
虽然删除是
富:〜富();
免费(...);
那么为什么new / delete最终会拥有自己的语法而不是常规函数呢?
这是一个刺戳:
新
运算符调用运算符new()
函数。同样, delete
运算符调用运算符delete()
函数(并且对于阵列版本类似)。
那么为什么这样呢?因为允许用户覆盖 operator new()
但 not new
运算符(这是一个关键字)。你可以重载 operator new()
(和delete)来定义你自己的分配器,但是你不负责(或者允许)调用适当的构造函数和析构函数。编译器在看到 new
关键字时自动调用这些函数。
没有这种二分法,用户可以重载运算符new()
函数,但编译器仍然必须将其视为特殊函数,并调用相应的构造函数正在创建的对象。
Why can't it just be regular function calls? New is essentially:
malloc(sizeof(Foo));
Foo::Foo();
While delete is
Foo:~Foo();
free(...);
So why does new/delete end up having it's own syntax rather than being regular functions?
Here's a stab at it:
The new
operator calls the operator new()
function. Similarly, the delete
operator calls the operator delete()
function (and similarly for the array versions).
So why is this? Because the user is allowed to override operator new()
but not the new
operator (which is a keyword). You override operator new()
(and delete) to define your own allocator, however, you are not responsible (or allowed to for that matter) for calling appropriate constructors and destructors. These function are called automatically by the compiler when it sees the new
keyword.
Without this dichotomy, a user could override the operator new()
function, but the compiler would still have to treat this as a special function and call the appropriate constructor(s) for the object(s) being created.
这篇关于为什么c ++对于new&删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!