简体   繁体   English

为什么“新”不是运算符,而是运算符?

[英]Why is 'new' an operator, not a function?

是否有与new相关的sizeof等问题,例如编译时间运算符?

new is an operator so you can overload it for some (or all) of your classes. new是一个运算符,因此您可以为部分(或全部)类重载它。

EDIT: I'll try to clarify to address @sbi's comments below. 编辑:我将尝试澄清以下地址@sbi的评论。

Consider two classes: 考虑两类:

class Base
{
}

class Derived : public Base
{
}

Let's assume that new() is a function, and we want to specialize it for the Base class and its descendants. 假设new()是一个函数,并且我们想专门针对Base类及其后代。 We would have the "basic" new() function: 我们将拥有“基本” new()函数:

void *new(size_t size);

Overloaded functions cannot differ by their return types alone, so we can't do: 重载函数不能仅凭其返回类型而有所不同,因此我们不能这样做:

Base *new(size_t size);  // Illegal.

We can't use member functions because they need an existing instance to be called. 我们不能使用成员函数,因为它们需要调用现有实例。 We could use static member functions: 我们可以使用静态成员函数:

class Base
{
    static Base *new();
}

But the resulting syntax when allocating a instance of Derived would be quite awkward: 但是,在分配Derived实例时产生的语法将很尴尬:

Derived *derived = Base::new();  // Uh?

I think the short answer to your question is that the new operator isn't a function, because it is the new that appears in a new-expression , and new-expression doesn't follow the function call syntax. 我认为您问题的简短答案是new运算符不是函数,因为它是new出现在new-expression中 ,并且new-expression不遵循函数调用语法。 How can it be a function, when one of the possible components/operand of a new-expression is a type-id ? new表达式的可能组件/操作数之一是type-id时,它如何成为函数? Could you define the syntax of a new-expression such that new would be a function, presumably overloaded on the type being allocated? 您是否可以定义new表达式的语法,使new成为一个函数,可能在分配的类型上重载了? And if you could, would Bjarne Stroustrup have preferred that syntax to the syntax he actually invented, and that ISO standardized? 而且,如果可以的话,Bjarne Stroustrup会更喜欢该语法而不是他实际发明的语法,并且将ISO标准化吗?

To be honest, I think that in everyday English the standard is pushing its luck classifying the new-expression as a "unary expression" at all. 老实说,我认为在日常英语中,该标准正在推动将新表达式归类为“一元表达式”的运气。 If it is, then its "single" operand consists of up to three separate parts ( new-placement , new-type-id , new-initializer ). 如果是,则其“单个”操作数最多由三个独立的部分组成( new-placementnew-type-idnew-initializer )。 Not that it really matters - it is what it is, and AFAIK the standard doesn't define any properties which apply to all operators, so it doesn't matter that much whether you call it an operator, or just a keyword used to introduce a new-expression . 并不是真的很重要-就是这样,并且AFAIK标准没有定义适用于所有运算符的任何属性,因此无论您将其称为运算符还是仅仅是用来引入关键字的关键字都没关系一个新表达式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM