Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different std::map size when inserting with operator[] (vc++ vs g++)

This code

#include <iostream>
#include <map>

int main()
{
    std::map<int, std::size_t> m;
    m[0] = m.size();
    std::cout << m[0] << std::endl;
}

will print 0 with vc++ and 1 with g++.

  • Is this code valid?
  • If yes, which compiler is correct?
  • Intuitively I would expect 1. How does vc++ end up with 0?
like image 736
AMA Avatar asked Dec 22 '22 15:12

AMA


1 Answers

Since C++17 the order of evaluation is guaranteed, m.size() is sequenced before m[0]; the result is guaranteed to be 0.

  1. In every simple assignment expression E1=E2 and every compound assignment expression E1@=E2, every value computation and side-effect of E2 is sequenced before every value computation and side effect of E1

Before C++17 the behavior is unspecified.

BTW you can observe different behaviors with Gcc C++17 mode and Gcc C++14 mode.

like image 94
songyuanyao Avatar answered Dec 26 '22 11:12

songyuanyao