Translations of this page?:

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 (or, when type is a class, to provide arguments to the constructor).

Allocating arrays can be accomplished by providing a size parameter in brackets (note that in this case no initializer can be given, so the type must be default-constructible).

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(). Perhaps the most useful argument is nothrow which does not throw an exception when there is no available memory. For example:

    Foo *foo; // Foo is a class, and foo is a pointer to an object of the Foo class
    foo = new(nothrow) Foo();
    assert( foo );

Alternately, the new() function can be overloaded for a class and then passed arbitrary arguments. For example:

    class Base {
    public:
      Base() { }
 
      void *operator new( size_t 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'

Remember to free any memory allocated with new with the delete operator. If you use the array version of the new operator, you will need to use the array version of the delete operator.

Related Topics: delete, free, malloc

 
• • • IndexRecent changesRSScc