lundi 3 août 2020

Is the result of indirectly mutating the same value twice per statement undefined?

As far as I know, C++ code like foo(++i, ++i) yields undefined behavior because it mutates i twice per "sequence point" (by the way, what's the new term for it?). But what if the same happens indirectly? Here's an example:

#include <iostream>

unsigned nextId = 0;
struct IdOwner {
  unsigned id;
  IdOwner() : id(nextId++) {} // mutates nextId
};

void test(IdOwner one, IdOwner two) {
  std::cout << one.id << " " << two.id << std::endl; // just observing
}

int main() {
  test(IdOwner{}, IdOwner{}); // indirectly mutates nextId twice per statement
}

Does that call to test() cause undefined behavior? For me it prints 1 0 which is fine (note: the order of computing function arguments is unspecified).

Aucun commentaire:

Enregistrer un commentaire