[Solved] What happens when operator new returns address in this code “new T”? [closed]


T *t = new T;
//     ^^^^^

This is a declaration of t of type T*. It is being initialized by the expression after the =. The entire new T part is the new-expression in this initializer.

The new-expression causes memory to be allocated for an object of type T and then that object is constructed in that space. The new-expression returns a pointer to that object. That is, after the new-expression has been evaluated, the line now looks like:

T *t = returned_pointer;

I assume you’re using 0x0FF00 as an example memory address – in which case, you can imagine the line has become:

T *t = 0x0FF00; // Note: this wouldn't actually compile because 0x0FF00 is an integer literal

The pointer t is now initialized with that memory address.

You might be confused by what exactly a new-expression does. It has these two steps:

  1. It calls the appropriate allocation function (typically operator new), passing the size of the memory it needs to store an object of type T. operator new allocates that memory and returns an address that points at that location.

  2. It then initializes an object of type T in that space.

solved What happens when operator new returns address in this code “new T”? [closed]