Tuesday, September 6, 2016

Dynamic memory allocator: new in C++

In c++ we will use new operator to allocate memory dynamically . In this post we will know how this process happens and what are the steps involved while using new. Basic syntax for new is
new [placemenet-params] typename;
This expression will allocate the memory available from the free store and returns the pointer to the object of type 'typename'. And in case of class, struct types it will allocate memory and intialise the object then retun the pointer to the object 'typename'.

Here 'placemenet-params' is optional and it will be usefull when we overload the new operator. This will be usefull particularly when hardware dependent objects to be allocated at a specified address.

Example:
int *p = new int;

char *arr = new char[10]; //for array of 10 chars

ExampleClass *obj = new ExampleClass();


> Call to new internally invokes 'operator new' function available globally to allocate memory for all types. If you overload operator new function for the particular class then the overloaded version will be called (operator new function of the class). This function will take size_t type as argument to allocate the number of bytes and returns the pointer to the object of typename.

 And we can pass any number of arguments to this overloaded operator new function which are passed as placemenet-params.

Ex: ExampleClass *obj = new (0x00AA) ExampleClass();

here (0x00AA) will be the extra parameter for the operator new function.

> If you want to meke a call to the globally available operator new function , rather the class specific operator new function used scope resolution(::) before new 

Example: Type-name t = ::new Type-name;

No comments:

Post a Comment