new
Syntax:
pointer = new type; pointer = new type( initializer ); pointer = new type[size]; pointer = new( arg-list ) type...
The new operator (valid only in C++) allocates a new chunk of memory to hold a variable of type type and returns a pointer to that memory. An optional initializer can be used to initialize the memory. Allocating arrays can be accomplished by providing a size parameter in brackets.
The optional arg-list parameter can be used with any of the other formats to pass a variable number of arguments to an overloaded version of new(). For example, the following code shows how the new() function can be overloaded for a class and then passed arbitrary arguments:
class Base { public: Base() { } void *operator new( unsigned int size, string str ) { cout << "Logging an allocation of " << size << " bytes for new object '" << str << "'" << endl; return malloc( size ); } int var; double var2; }; ... Base* b = new ("Base instance 1") Base;
If an int is 4 bytes and a double is 8 bytes, the above code generates the following output when run:
Logging an allocation of 12 bytes for new object 'Base instance 1'
Related topics: