-13
   string *ptr = new string("Hello");

What happens when we call the new operator? explain in simple points.

glennsl
  • 28,186
  • 12
  • 57
  • 75
  • 5
    I highly doubt your question is a good fit for this website. Please consult: http://stackoverflow.com/help/how-to-ask. Being polite also helps. –  Mar 25 '15 at 07:40
  • 1
    What have you researched yourself, what exactly don't you understand? As this is a fairly beginner-level question, I assume you're learning from a [good book](http://stackoverflow.com/q/388242/1782465) or tutorial. How was it explained there and what parts of that explanation are unclear? – Angew is no longer proud of SO Mar 25 '15 at 07:46

2 Answers2

0
string *ptr = new string("Hello");

The new operator mainly does two things:

  1. It allocates enough memory to hold an object of the type requested. (In the above example, it allocates enough memory to hold this string object)

    1. It calls a constructor to initialize an object in the memory that was allocated.

Now this “new” is calling which function?

It is operator new.

void * operator new (size_t size);

The return type is void*. Since this function returns a pointer to raw which is not typed and uninitialized memory large enough to hold an object of the specified type. The size_t specifies how much memory to allocate.

If we call operator new directly , it returns a pointer to a chunk of memory enough to hold a string object.

void *pointRawMemory = operator new(sizeof(string));

The operator new is similar to malloc. It is responsible only for allocating memory. It knows nothing about constructors. It is the job of the “new” operator to take the raw memory that the operator new returns and make it into an object.

DeepN
  • 344
  • 2
  • 13
0

A string object is allocated in the dynamic storage area and its constructor is called (the one receiving a const char *).

Then the result of that constructor (the address of the object) is placed into the ptr variable, which may exist in one of many different storage areas (such as static storage area or on the stack), depending on where that statement actually is in your code.

That's really all you need to know, everything "under" that is an implementation detail.

In terms of the difference between operator new and new, the former operates at a lower level of abstraction, simply allocating enough memory to store something, and not calling any constructors.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953