0

In another forum someone claimed that with the following code ...

f( shared_ptr<A>( new A() ), shared_ptr<A>( new B() ) )

... C++ is allowed to evaluate the two news before assigning their return-value to the shard_ptrs and thereby producing a memory-leak when the second new (in whatever order they are executed) throws an exception. I can't believe this because it would be too easy to define the language in a way that this wouldn't happen.

Is this really true?

  • 3
    Yes, it is true. – Jesper Juhl Apr 28 '18 at 19:05
  • @JesperJuhl No answers in comments please :-) – juanchopanza Apr 28 '18 at 19:06
  • 3
    "*I can't believe this because it would be too easy to define the language in a way that this wouldn't happen.*" Hah. Wait until you see the rest of the language. For example, if you don't explicitly initialize (local) variables of built-in type, they contain garbage. – melpomene Apr 28 '18 at 19:07
  • 1
    @melpomene That's still not as bad as my pet peeve [Do I need to cast to unsigned char before calling toupper?](//stackoverflow.com/q/21805674) That is a *really* stupid gotcha IMO. – Baum mit Augen Apr 28 '18 at 19:09
  • 3
    Is this really a duplicate? The question isn't asking whether A or B is evaluated first. It's asking whether the evaluation of one operand has to be completed before the other operand is begun. – Hong Ooi Apr 28 '18 at 19:10
  • @BaummitAugen: along with the fact that the signedness of plain `char` is implementation-defined. Or that in most implementations it is signed by default. – Matteo Italia Apr 28 '18 at 19:19
  • 1
    As it turns out the answer depends on which version of C++ you're using: https://stackoverflow.com/questions/38501587/what-are-the-evaluation-order-guarantees-introduced-by-c17/46472497#46472497 – Hong Ooi Apr 28 '18 at 19:32
  • 3
    it was changed in C++17 that [order is still unspecified but nested parameter evaluation cannot be interleaved](https://stackoverflow.com/a/46472497/2189130) – kmdreko Apr 28 '18 at 19:32

0 Answers0