Linux vs Windows std::map assignment constructors (Why such a difference?)

僤鯓⒐⒋嵵緔 提交于 2019-12-10 18:25:07

问题


I was witnessing some unexpected behavior in a C++ application I am writing in Linux Ubuntu. I would construct an object with parameters and then put a copy of that object into a 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 am just printing out which constructor/operator gets called in what order so I can see how the construction and assignment works in the "main" function.

When I run this in Windows I get my expected output...

Param
Default
Assignment

When I run this in Linux I get the following output...

Param
Default
Copy
Copy
Assignment

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

Thanks!


回答1:


The answer lies in stl_map.h. Its behaviour depends on whether you compile with C++11 support or not. If you do then the STL can take advantage of 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 -std=c++11 in newer versions.

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

Param
Default
Assignment

Edit: Thank you very much for clarifying for me that my assumption that this was down to move semantics was incorrect. I'm leaving this answer in place to direct users to this better one.



来源:https://stackoverflow.com/questions/18663963/linux-vs-windows-stdmap-assignment-constructors-why-such-a-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!