C++ Memory management

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Syntax

  • ::(opt) new (expression-list)(opt) new-type-id new-initializer(opt)
  • ::(opt) new (expression-list)(opt) (type-id) new-initializer(opt)
  • ::(opt) delete cast-expression
  • ::(opt) delete [] cast-expression
  • std::unique_ptr<type-id> var_name(new type-id(opt)); //C++11
  • std::shared_ptr<type-id> var_name(new type-id(opt)); //C++11
  • std::shared_ptr<type-id> var_name = std::make_shared<type-id>(opt); //C++11
  • std::unique_ptr<type-id> var_name = std::make_unique<type-id>(opt); //C++14

Remarks

A leading :: forces the new or delete operator to be looked up in global scope, overriding any overloaded class-specific new or delete operators.

The optional arguments following the new keyword are usually used to call placement new, but can also be used to pass additional information to the allocator, such as a tag requesting that memory be allocated from a chosen pool.

The type allocated is usually explicitly specified, e.g., new Foo, but can also be written as auto (since C++11) or decltype(auto) (since C++14) to deduce it from the initializer.

Initialization of the object allocated occurs according to the same rules as initialization of local variables. In particular, the object will be default-initialized if the initializer iso omitted, and when dynamically allocating a scalar type or an array of scalar type, there is no guarantee that the memory will be zeroed out.

An array object created by a new-expression must be destroyed using delete[], regardless of whether the new-expression was written with [] or not. For example:

using IA = int[4];
int* pIA = new IA;
delete[] pIA;  // right
// delete pIA;  // wrong


Got any C++ Question?