我正在阅读Josuttis的“使用Map作为关联数组”(来自C++标准库-教程和参考,第二版),并在Stack Overflow上发现了将std::map用作关联数组。现在我对插入到map中调用的构造函数有更多疑问。
这是我的示例程序(不使用最佳编码实践,请原谅我):
这个程序的输出是:
我原以为通过索引初始化map应该调用默认构造函数,然后再调用赋值运算符。但执行
这是我的示例程序(不使用最佳编码实践,请原谅我):
class C
{
public:
string s;
C() { cout << "default " << endl;}
C(const string& p) : s(p)
{ cout << "one param" << endl;}
C(const C& obj)
{
if (this != &obj)
{
s = obj.s;
}
cout << "copy constr" << endl;
}
C& operator = (const C& obj)
{
if (this != &obj)
{
s = obj.s;
}
cout << "copy initializer" << endl;
return *this;
}
};
int main()
{
map<int,C> map1;
C obj("test");
cout << "Inserting using index" << endl;
map1[1] = obj;
cout << "Inserting using insert / pair" << endl;
map1.insert(make_pair(2,obj));
}
这个程序的输出是:
one param
Inserting using index
default
copy constr
copy constr
copy initializer
Inserting using insert / pair
copy constr
copy constr
copy constr
copy constr
我原以为通过索引初始化map应该调用默认构造函数,然后再调用赋值运算符。但执行
map1[1] = obj
会产生以下输出;Inserting using index
default
copy constr
copy constr
copy initializer
有人可以帮我更好地理解初始化吗?