129

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

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Sandeep
  • 2,737
  • 5
  • 21
  • 17
  • 3
    Hi, can you please clarify the question? Looks like there is typo somewhere. – Dima Malenko Dec 11 '09 at 04:54
  • 17
    The question is worded correctly, see answers below. The method for dynamically allocating memory is to use the `new` operator. This operator can be overloaded. To distinguish between the default operator and an overloaded version, the default is called "new operator" and the overloaded version is called "operator new". – Thomas Matthews Dec 11 '09 at 18:55
  • 2
    How to do that. I am new and unaware. – Sandeep Dec 23 '09 at 08:48

8 Answers8

133

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

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));

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

void *operator new(size_t);

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);

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.

Jerry Coffin
  • 437,173
  • 71
  • 570
  • 1,035
  • 19
    +1, as to a different phrasing, the standard uses *new expression* all around, and only once it uses *new operator* to refer to the place of call. I tend to do the same: *operator new* for the *allocator* and *new expression* for the use. – David Rodríguez - dribeas Mar 16 '11 at 19:19
  • 3
    A new expression is the whole phrase that begins with new. So what do you call just the "new" part of it? If it's wrong to call that the new operator, then we should not call "sizeof" the sizeof operator, or & the address-of operator (when it behaves like one). – Kaz Mar 07 '12 at 08:44
  • 1
    Following up on Kaz's remark, perhaps the question should be rephrased as, What's the difference between the new operator and the operator new operator? :) – C S Dec 24 '12 at 00:09
  • This probably sounds silly, but is there any way to overload the `new` operator? – user541686 May 07 '13 at 21:40
  • 1
    @Mehrdad: You can overload `operator new` and `operator new[]`, (the allocators) but not the `new` operator itself. – Jerry Coffin May 07 '13 at 21:44
  • 3
    "operator new" vs "new keyword" – user997112 Aug 08 '14 at 12:27
  • If one allocates a chunk of memory as you did in your first line of code, what would be the correct way to release that memory? – antred Oct 30 '14 at 10:49
  • 2
    @antred: You'd release that with something like `operator delete(x);`. – Jerry Coffin Oct 30 '14 at 13:25
  • `placement new` `new expression` and `new operator` are same thing, while `operator new` is distinct. – metablaster May 04 '20 at 21:30
37

"operator new"

class Foo
{
public:
        void* operator new( size_t );
}

"new operator":

Foo* foo = new Foo();

In this example, new Foo() calls Foo::operator new()

In other words, "new operator" calls "operator new()" just like the + operator calls operator +()

Ashwin Nanjappa
  • 68,458
  • 72
  • 198
  • 283
Austin Hyde
  • 23,947
  • 28
  • 88
  • 124
  • 15
    `new` is not an operator in C++. `sizeof`, for example, is an operator, but `new` and `delete` are not. `new` and `delete` are keywords and the syntactical constructs that these keywords form are called *new-expression* and *delete-expression*. – AnT Dec 11 '09 at 05:16
  • 3
    Uh, if anything, `sizeof` is the syntactic construct, and `new` and `delete` are both valid, legal, overload-able operators. From everything I've ever seen, `new` and `delete` are both operators. See [cplusplus.com][http://cplusplus.com/doc/tutorial/classes2/] – Austin Hyde Dec 11 '09 at 05:28
  • 7
    Incorrect. The official C++ terminology is the terminology defined by the language specification, not by some web site. In the language specification there's no such therm as "new operator", but there's such term as "`operator new` function". Again, `sizeof` is explicilty referred to as an "operator", while `new` and `delete` are *never* referred to as operators. – AnT Dec 11 '09 at 06:14
  • 7
    AndreyT: Incorrect. The C++ standard does call 'new' an operator, see 13.5/1. –  Dec 11 '09 at 07:35
  • In the context of operator-overloading, it's an operator. But 5.3.3 starts "The `sizeof` operator...", and 5.3.4 starts "The *new-expression*...". Go figure. Neither one of them is a *unary-operator* in 5.3. – Steve Jessop Dec 11 '09 at 14:17
  • As Roger Pate correctly points out, new and delete are operators along with: new delete new[] delete[] + - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= && || ++ -- , ->* -> () [] Notice that sizeof is not between. see: http://www.kuzbass.ru:8086/docs/isocpp/over.html#over.oper – Tommy Andersen Dec 11 '09 at 19:22
  • @Roger: Incorrect. Whay you quoted is a piece of C++ language *grammar*. The word `operator` in this case is just a non-terminal symbol of the grammar, not a term. They could have called it `grandmas-cookie` with the same degree of success. All this means is that function-id `operator new` is handled by the same branch of grammar that is used for real operators, but in no way it means that `new` is also an operator. The `Note:` bit that follows the grammar is non-normative, so they took certain liberties there. – AnT Dec 11 '09 at 22:10
  • 2
    So, can we agree that for this **specific** question that `new` is an operator? In day-to-day use, does it *really* matter that `new` is actually an expression defined *like* an operator? I understand AndreyT's point, and see how the definition is important, but only in the context of, say, how the compiler interprets it, NOT in this case. – Austin Hyde Dec 11 '09 at 23:03
  • 2
    Well, I agree. But when I look at the original question, that is what I see: a purely *terminological* question. Terminological questions are supposed to be pedantic, in my opinion. – AnT Dec 11 '09 at 23:21
  • AndreyT: I was pointing out how your statement that "new and delete are never referred to as operators" is incorrect. The standard is great for many things, but not everything. –  Dec 12 '09 at 17:29
  • 3
    @AndreyT: I thought as you do, that *operator new* was the *allocator* and *new-expression* the uses. I reviewed and checked that in §5.3.4/3 the current standard uses the term *new operator*. Later in §5.3.4/8 it names the allocator functions as *operator new* and *operator new[]* – David Rodríguez - dribeas Mar 16 '11 at 19:30
23

Following is the quote from More Effective C++ book from Scott Meyers:

The new operator calls a function to perform the requisite memory allocation, and you can rewrite or overload that function to change its behavior. The name of the function the new operator calls to allocate memory is operator new.

Naveen
  • 69,046
  • 43
  • 164
  • 225
  • 7
    The term is obviously invented by the author of the book (or,maybe, borrowed from some obsolete source). In formal C++ nomenclature there's no such term as "new operator". – AnT Dec 11 '09 at 05:18
  • 3
    @AndreyT: I did a search of the C++11 for "new operator" and found it referenced in four places. Specifically, two references to the "placement new operator" – Mooing Duck Feb 11 '15 at 18:56
10

There's no difference between "new operator" and "operator new". Both refer to the same thing: the overloadable/replaceable operator new function that typically performs raw memory allocation for objects created by new-expressions.

Note also that neither term is present in the language specification (which is the defining source of the official terminology).

When you use new in your program to create an object, it is called new-expression. New-expression consists of keyword new and additional syntactic parts defined by the grammar. No part of this expression's syntax is ever referred to as an "operator".

The raw memory allocation function operator new is officially referred to as just "operator new function". Note that the words operator and new in this sequence are just two separate C++ language keywords. They don't form an English term "operator new". Nowhere in the language specification you'll find any references to "operator new" as an English term. Every time this is just a combination of two independent keywords that produce declaration syntax for a memory allocation function.

Again, in resume: formally in C++ there's no such English language terms as "operator new" or "new operator". The former sequence is present in the language specification as a mere combination of keywords, not as an English term. The latter is not present at all.

AnT
  • 291,388
  • 39
  • 487
  • 734
  • 15
    You seem lost in some pedantic mental-masturbation. The standard is vague in spots, and this is one of them. It makes just as much sense to "discuss the new operator" as it does to "discuss the plus operator" or "discuss the + operator". –  Dec 11 '09 at 07:39
8

When you create a new object the memory is allocated using operator new then the constructor is invoked to initialise the memory. The new operator does both the allocation and the initialisation, where as the operator new only does the allocation.

Chris Fulstow
  • 38,141
  • 9
  • 83
  • 109
7

The OP's question is not phrased properly. It's better to phase as 'Difference between 'operator new' and 'new expression'?' Note 'operator new' often refers to 'operator new function' as well.

And there are plenty correct answer around, below is mine:

1> 'new expression' call 'operator new' to allocate raw memory,then call constructor

apple * p = new apple(); //new expression

2> 'operator new' only allocate raw memory, not much difference than malloc

void* mem = operator new(sizeof(apple)); //just like calling malloc()
apple* p2 = new(mem) apple(1); //call construct here using placement new.
Gob00st
  • 5,279
  • 6
  • 40
  • 69
2

The new operator: C++ supports dynamic allocation of objects using the new operator. The new operator allocate memory for objects from a pool called the free store. The new operator calls the special function operator new.

operator new: If the request is for zero bytes of storage, operator new returns a pointer to a distinct object (that is, repeated calls to operator new return different pointers). If there is insufficient memory for the allocation request, operator new returns NULL or throws an exception. The first argument to operator new must be of type size_t (a type defined in STDDEF.H), and the return type is always void *.

Here is a MSDN links for more details:

The operator new Function

The new Operator

aJ.
  • 32,074
  • 21
  • 79
  • 124
  • 1
    Slight clarification: the non-placement operator new must always throw on allocation failure (according to the standard); and placement forms, such as `::new(std::nothrow)`, can do either (that specific example returns a null pointer). –  Dec 21 '09 at 21:49
1
  1. new is an operator as well as a keyword.

    see [1] In 2.13 && In 2.12.

  2. new does two things: T* t = new T(arg);

    1)allocate memory for the object: void* ptr = operator new(sizeof(T));

    //operator new is a function(just like malloc in c), not an operator.(see [1] In 3.7.4 ). But Item 7 [2] said it is an operator too. In my opinion, the difference between operator and function is small, and you can see it when you recall that overloading operator is implemented by functions.

    //we can overload this operator/function(operator new) doing what we want just here.

    2)initialize the object in the allocated memory: call T::T(arg) on ptr

    //only compiler can do this. Neither me nor you can.

    //also compiler will invoke member objects' constructors and base class's constructor if T has them. And this invocation is recursive. Only compiler can do that.

  3. So, operator new does part of the missions of new, and only in this part we can do something.

    [1]: ISO/IEC, N3690. http://ww.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3690.pdf

    [2]: Meyers, Scott. Effective C++, 3rd.

njuhgn
  • 11
  • 2