Ivan Akulov
Ivan Akulov

Reputation: 4323

Meaning and examples of "new (expr-list) type" operation

In “The C++ Programming Language” book, in list of operations (article 6.2), Bjarne Stoustrup wrote this:

create (place) new ( expr-list ) type

create (place and initialize) new ( expr-list ) type ( expr-list )

I’ve never heard about this kind of the new operator, and I’m interested what does it do.

Upvotes: 4

Views: 164

Answers (2)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507095

It does what you tell it to do. Some people use it to pass an allocator environment and alignments. For example in a language runtime I wrote I do

new (myEnvironment) Variable(initialValue);

The clang compiler associates allocated AST resources with an "ast context", so it does something like

new (AstContext, 32 /* alignment */) MyFooBar;

The arguments are all passed as a single argument list to an overloaded operator new, with the size requested as a first argument prefixed before them.

Upvotes: 1

Kiril Kirov
Kiril Kirov

Reputation: 38173

This is called placement-new. You can create an object over already existing memory.

Here's an explanation and an useful question in SO

You can also have nothrow, for example:

char* pzNewBuffer = new (nothrow) char [2048];

which tells, that new will not throw std::bad_alloc in case of out of memory, but it will return NULL, instead.


Another example, that comes to my mind - the standard containers (probably) use placement new: when you call reserve, memory is allocated, but nothing is constructed/initialzed on this memory. So, when you insert (with std::vector<T>::push_back for example), if there's allocated, but not initialized memory - placement new is used.

Upvotes: 3

Related Questions