Consider the following line of code:
new (p++) T();
If the constructor T()
throws an exception, is p
guaranteed to have already been incremented?
Consider the following line of code:
new (p++) T();
If the constructor T()
throws an exception, is p
guaranteed to have already been incremented?
From 5.3.4 [expr.new] (quoting from n3242):
11 The new-placement syntax is used to supply additional arguments to an allocation function. If used, overload resolution is performed on a function call created by assembling an argument list consisting of the amount of space requested (the first argument) and the expressions in the new-placement part of the new-expression (the second and succeeding arguments).
So in a new expression the allocation function is used from a function call (which makes sense). All allocation functions are functions, including the ones provided by the implementation, from 3.7.4.1 [basic.stc.dynamic.allocation]:
1 An allocation function shall be a class member function or a global function; [...]
So by the time an exception is thrown from the constructor, the allocation has taken place and the associated function call expression has been fully evaluated.
Yes it is guaranteed to be incremented.
The operators are just syntactic sugar for function/method calls.
I don't believe new has any special meaning above operator so it should be the same.
Thus all parameter are fully evaluated (with sequence point) before the function new
is called.
I don't think the standard answers this question directly/explicitly. Implicitly, however, the answer is yes.
In particular, the placement syntax for new is simply a way of specifying extra parameters that will be passed to a function. Like any other function call, there is a sequence point between evaluating all the parameters to the function (in unspecified order), and executing any code in the function. I believe that should mean your p++
will be evaluated and all side effects applied before anything else happens.
Placement new is just a regular function, named operator new(size_t, void*)
. It simply returns its second argument.
operator new
. –
Akkadian The increment operator does the following:
So, p
is guaranteed to be incremented.
© 2022 - 2024 — McMap. All rights reserved.
new (p) T(); ++p;
because it is easier to understand and the differing semantics (no increment when exception is thrown) fit my program logic better. – Akkadian