Is initializer evaluated after memory allocation in new expression?
Asked Answered
P

1

7

Consider the code

auto p = new T( U(std::move(v)) );

The initializer is then U(std::move(v)). Let's assume that T( U(std::move(v)) ) does not throw. If the initializer is evaluated after the underlying memory allocation, the code is then strong-exception-safe. Otherwise, it is not. Had memory allocation thrown, v would have already been moved. I'm therefore interested in the relative order between memory allocation and initializer evaluation. Is it defined, unspecified, or what?

Provincetown answered 4/4, 2018 at 8:23 Comment(2)
If your interest is exception safety of new expressions, you may be interested to know (if not already) that there are case of new expression (using user defined allocation funciton) that can cause memory leaks: [expr.new]/21Zincate
Obviously, the memory has to be allocated to move something into it (or initialize it)!Armallas
F
8

Yes, the initialisation is evaluated after the allocation. Quoting C++17 (N4659) [expr.new] 8.3.4/19:

The invocation of the allocation function is sequenced before the evaluations of expressions in the new-initializer. Initialization of the allocated object is sequenced before the value computation of the new-expression.

Fruge answered 4/4, 2018 at 8:36 Comment(1)
Right on target, bro!Provincetown

© 2022 - 2024 — McMap. All rights reserved.