0

This should be a quite elementary question...

Let a be a variable of type T, and f() be any kind of function which returns T (or T&, or anything that can be assigned to T). Now, assume f() does not modify a. Consider:

a = f();

For T to be a user-defined type, I can be sure that a will only be modified after the evaluation of f() has finished. Because a = f(); is a call of the operator=() function, and the execution will not go into the function body before the argument is evaluated.

For T to be a built-in type, may I ask if the data in a is never modified before the evaluation of f() is finished?


The reason that I would like to confirm this is because I really want to make sure that in any cases where such a f() throws an exception, we can safely say that the data in a is not corrupted.

CPPL
  • 726
  • 1
  • 10
  • 1
    "*For `T` to be a built-in type, may I ask if the data in `a` is never modified before the evaluation of `f()` is finished?*" - yes, that is true. You can't assign something to `a` if that something doesn't exist yet. So `f()` has to be evaluated first, always – Remy Lebeau Sep 07 '22 at 19:32
  • It depends on your version of C++. In C++17, there is a defined order. Before that, it is unspecified. – NathanOliver Sep 07 '22 at 19:32
  • 1
    @NathanOliver The evaluation order doesn't matter here, the compiler is not allowed to write junk to `a` before doing the proper assignment. – HolyBlackCat Sep 07 '22 at 19:34
  • @HolyBlackCat It can't write junk, but the order in which each side is resolved can matter, for example: https://stackoverflow.com/questions/67233792/inserting-its-own-size-to-stdmap (yes doesn't apply to the OPs specific example) – NathanOliver Sep 07 '22 at 19:36
  • 2
    @NathanOliver I believe that question confirms that `a` may be evaluated before `f()`, but - pertaining to this question - the `=` is always evaluated after both operands are evaluated. – Drew Dormann Sep 07 '22 at 19:37

0 Answers0