Are there any issues, like compile time opera开发者_StackOverflowtor, with sizeof associated with new?
new
is an operator so you can overload it for some (or all) of your classes.
EDIT: I'll try to clarify to address @sbi's comments below.
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. We would have the "basic" new()
function:
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 = 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. How can it be a function, when one of the possible components/operand of a new-expression is a 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? And if you could, would Bjarne Stroustrup have preferred that syntax to the syntax he actually invented, and that ISO standardized?
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). 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.
精彩评论