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:
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*?
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:
EDIT: Per ArunSaha's suggestion, updated the test. The insert() output is unchanged, while the assignment sequence looks like this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With