std::exchange working differently with VC++ and gcc

following code:

#include <utility>

int main()
  auto pos = 0;
  auto rel = pos - std::exchange(pos, pos + 1);

  return rel; // g++: 0, VC++: 1

If you try the code on rextester with the VC++ compiler then the result is 1, with gcc on godbolt the result is 0 (results are apparently not returned with gcc using rextester).

Question: Why are the results different?

And 2nd question: Are there any tools to check for that mistake? Any clang warnings?

My guess is that std::exchange in VC++ is called before the other operand is evaluated, whereas in gcc this is not the case. If you swap the operands pos and std::exchange the result is -1 (or 255) both VC++ and with gcc.

It is probably something about side effects - and calling std::exchange which clearly has a side-effect.

Fortunately I caught the bug with a unit test after transitioning from VC++ to gcc - and was a bit flustered at first and boiled it down to this simple (not) working example.

Read more here:

Content Attribution

This content was originally published by michael_s at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: