Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL Map Value Constructors

Tags:

c++

stl

I have a class X that I would like to put into an STL map of type std::map. An STL map needs to have X stored in memory somewhere so I'm looking for an efficient (run time and memory) way to create X and store it in the map.

I noticed that the following code where x is an object of type X and stlMap is a map of type std::map:

stlMap["test"] = x;

Results in the following being called:

  1. X default constructor
  2. X Copy constructor
  3. X Copy constructor
  4. X destructor
  5. X destructor
  6. X assignment constructor
  7. X destructor

Why are so many X objects being created?

Is it an inefficient use of time and memory?

Is there a better way to put an object into a map? Maybe changing the map to be a map of strings to x*?

like image 814
C Nielsen Avatar asked Apr 06 '26 05:04

C Nielsen


1 Answers

Try stlMap.insert( map<string, X>::value_type("test", x) ):

#include <iostream>
#include <string>
#include <map>

using namespace std;

class X
{
public:
X() { cout << "X default constructor" << endl; }
~X() { cout << "X destructor" << endl; }
X( const X& other ) { cout << "X copy constructor" << endl; }
X& operator=( const X& other ) { cout << "X copy-assignment operator" << endl; }
int x;
};


int main()
{
X x;
map< string, X > stlMap;

cout << "INSERT BEGIN" << endl;
stlMap.insert( map< string, X >::value_type( "test", x ) );
cout << "INSERT END" << endl;
stlMap.clear();
cout << "ASSIGN BEGIN" << endl;
stlMap["test"] = x;
cout << "ASSIGN END" << endl;

return 0;
}

On my g++ that whittles things down to:

  1. X copy constructor
  2. X copy constructor
  3. X destructor

EDIT: Per ArunSaha's suggestion, updated the test. The insert() output is unchanged, while the assignment sequence looks like this:

  1. X default constructor
  2. X copy constructor
  3. X copy constructor
  4. X destructor
  5. X destructor
  6. X copy-assignment operator
like image 151
genpfault Avatar answered Apr 08 '26 20:04

genpfault