Linux vs Windows std :: map assignment constructors (why is there such a difference?)

I have witnessed some unexpected behavior in a C ++ application that I write in Linux Ubuntu. I would build an object with parameters, and then put a copy of this object in std :: map using the assignment operator. I wrote a simple program to demonstrate this situation ...

#include <iostream> #include <string> #include <map> using namespace std; class Foo { public: Foo(void) : _x(0) { cout << "Default" << endl; } Foo(int a) : _x(a) { cout << "Param" << endl; } Foo(Foo const &foo) : _x(foo._x) { cout << "Copy" << endl; } Foo& operator=(Foo const &foo) { cout << "Assignment" << endl; if (this != &foo) { _x = foo._x; } return *this; } int get(void) { return _x; } private: int _x; }; int main(int argc, char *argv []) { std::map<int, Foo> foos; Foo a_foo(10); foos[100] = a_foo; return 0; } 

Here I just print out which constructor / operator is called in what order, so I see how the construction and assignment work in the "main" function.

When I run this on Windows, I get the expected result ...

Param
Default
Appointment

When I run this on Linux, I get the following output ...

Param
Default
Copy
Copy
Appointment

Why are there two additional copy constructors? It seems very inefficient to create an object so many times?

Thanks!

+3
source share
1 answer

The answer lies in stl_map.h. Its behavior depends on whether you are compiling C ++ 11 support or not. If you do, STL can take advantage of the move semantics to avoid unnecessary copying. VC ++ uses the new language features by default, but if you use g ++ or clang, you need to get used to using the -std=c++0x flag in 4.2 or the -std=c++11 in new versions.

With -std=c++11 set the output using g ++ 4.8:

 Param Default Assignment 

Edit: Thank you very much for clarifying to me that my assumption that this was due to the movement of semantics was wrong. I leave this answer in place to direct users to this best option .

-1
source

Source: https://habr.com/ru/post/988652/


All Articles