AMA
AMA

Reputation: 4214

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++.

Upvotes: 4

Views: 116

Answers (2)

songyuanyao
songyuanyao

Reputation: 172924

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.

Upvotes: 7

Marek R
Marek R

Reputation: 37707

Assignment operators - cppreference.com

When the left operand has reference type, the assignment operator modifies the referred-to object.

If the left and the right operands identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same)

Upvotes: 3

Related Questions