[英]new() and delete() as operators in C++?
What is the use or what is the reason for new() and delete() to be implemented as operators in c++ ? 将new()和delete()用作c ++中的运算符的用途是什么?原因是什么? What are the advantages of making it an operator instead of a function?
使它成为运算符而不是函数的优点是什么?
The new
operator cannot be a function because it accepts a type as an argument. new
运算符不能是函数,因为它接受类型作为参数。 You cannot write new foo_type
as a function call, because foo_type
is not an expression that produces a value, but a type name. 您不能将
new foo_type
编写为函数调用,因为foo_type
不是产生值的表达式,而是类型名称。
The delete
operator could be a function that is overloaded for different pointer types, and an extra optional bool
argument for delete []
semantics. delete
运算符可以是针对不同指针类型重载的函数,以及用于delete []
语义的额外可选bool
参数。 Why there is a delete
operator is probably for symmetry with its new
counterpart. 为什么要有
delete
运算符,可能与它的new
运算符是对称的。
That said, template functions can take types as template arguments. 也就是说,模板函数可以将类型作为模板参数。 But the
new
and delete
operators historically precede templates. 但是
new
和delete
运算符历来在模板之前。
Also, a function can be written which takes, instead of a type, a prototype instance of a type, from which an object is constructed: newobj(m_class(constructor_arg))
. 另外,可以编写一个函数,该函数采用一个类型的原型实例(而不是类型)来构造对象:
newobj(m_class(constructor_arg))
。 This newobj
is overloaded for different types. 对于不同类型,此
newobj
重载。 It allocates space, copy constructs into it, and returns the object. 它分配空间,将构造复制到其中,然后返回对象。
So in the end, the design reflects the tastes and whims of the designer. 因此,最终,设计反映了设计师的品味和异想天开。
The separation itself between operators and functions (and statements, declarations, and so on) is not strictly necessary in language design. 在语言设计中,操作符和函数(以及语句,声明等)之间的分隔本身并不是严格必须的。
There are two common reasons that I know of that people override them. 我知道人们优先考虑它们有两个普遍的原因。
1) Use new/delete to keep track of a pool of objects. 1)使用new / delete跟踪对象池。 New grabs the first unused resource from the pool, delete returns that resource to the pool.
New会从池中获取第一个未使用的资源,Delete将其返回到池中。 This is useful if you're constantly allocating/deallocating objects.
如果您经常分配/取消分配对象,这将很有用。
2) Tracking memory usage. 2)跟踪内存使用情况。 You can track down leaks or memory overwriting issues.
您可以跟踪泄漏或内存覆盖问题。 You could pad the memory on either side for instance, or keep track of who is allocating memory so you can track who didn't deallocate it.
例如,您可以在任一侧填充内存,或者跟踪谁在分配内存,以便跟踪谁没有取消分配内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.