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!
source share