我有一个 X 类,我想将其放入 std::map 类型的 STL 映射中。 STL map 需要将 X 存储在内存中的某处,因此我正在寻找一种有效的(运行时和内存)方式来创建 X 并将其存储在 map 中。
我注意到下面的代码,其中 x 是 X 类型的对象,而 STLMap 是 std::map 类型的映射:
stlMap["test"] = x;
调用以下内容的结果:
- X 默认构造函数
- X拷贝构造函数
- X拷贝构造函数
- X析构函数
- X析构函数
- X赋值构造函数
- X析构函数
为什么要创建这么多 X 对象?
这是对时间和内存的低效利用吗?
有没有更好的方法将对象放入 map 中?也许将映射更改为字符串到 x* 的映射?
最佳答案
尝试 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;
}
在我的 g++ 上,将事情简化为:
- X拷贝构造函数
- X拷贝构造函数
- X析构函数
编辑:根据 ArunSaha 的建议,更新了测试。 insert() 输出没有改变,而赋值序列如下所示:
- X 默认构造函数
- X拷贝构造函数
- X拷贝构造函数
- X析构函数
- X析构函数
- X复制赋值运算符
关于c++ - STL 映射值构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3771449/