In the following code sample, do the C++ standard guarantee that '++i' is evaluated after the memory allocation (call to operator new) but before the call to X’s constructor?
new X( ++i )
In the following code sample, do the C++ standard guarantee that '++i' is evaluated after the memory allocation (call to operator new) but before the call to X’s constructor?
new X( ++i )
From my copy of n2798:
5.3.4 New
21 Whether the allocation function is called before evaluating the constructor arguments or after evaluating the constructor arguments but before entering the constructor is unspecified. It is also unspecified whether the arguments to a constructor are evaluated if the allocation function returns the null pointer or exits using an exception.
Read in conjunction with (to avoid ambiguities):
5.3.4 New
8 A new-expression obtains storage for the object by calling an allocation function (3.7.4.1). If the newexpression terminates by throwing an exception, it may release storage by calling a deallocation function (3.7.4.2). If the allocated type is a non-array type, the allocation function’s name is operator new and the deallocation function’s name is operator delete. If the allocated type is an array type, the allocation function’s name is operator new[] and the deallocation function’s name is operator delete[]. [...]
This pretty much answers the question. The answer is 'No'.
In general, the C++ compiler is free to re-order function parameters as long as it does not alter the meaning.
See Martin's answer here: What are all the common undefined behaviours that a C++ programmer should know about?
There are actually 2 function calls going on here under the hood.
Even though it's two separate calls, I do not believe there is a sequence point between these two operations. Wikipedia appears to support this point. Therefore the Compiler is free to reorder evaluation as it sees fit.
++i should be performed before allocation AND call.
EDIT: (and I may have answered a bit too quickly)
new X( ++i )
The syntax for new operator wrt C++ standard:
[::] "new" ["(" expression-list ")"] {new-type-id | "(" type-id ")"} ["(" expression-list ")"]
So,
so, we can sure that, ++i will be evaluated, before the constructor of Object X is invoked.
Cheers..