首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

问一下地图析构类的有关问题

2014-01-15 
问一下map析构类的问题class A { public:A() { cout create A endl}~A() {cout destroy A

问一下map析构类的问题


class A {
 public:
  A() { cout << "create A" << endl;}
  ~A() {cout << "destroy A" << endl;}
};

int test3(){
  map<string, A> m;
  A a1;
  m["aaa"]=a1;
  cout << "to clear" << endl;
  m.clear();
  cout << "clear done" << endl;
}


这段代码的输出为:
create A
create A
destroy A
destroy A
to clear
destroy A
clear done
destroy A

问一下,为什么输出的前4行会有两次create 和 destroy A。 
在调用m.clear()时A已经析构了,为什么clear done后又会有一个destroy A。
谢谢。
[解决办法]
mapped_type& operator[](const key_type& _Keyval)
{// find element matching _Keyval or insert with default mapped
iterator _Where = this->lower_bound(_Keyval);
if (_Where == this->end()

[解决办法]
 this->comp(_Keyval, this->_Key(_Where._Mynode())))
_Where = this->insert(_Where,
value_type(_Keyval, mapped_type()));
return ((*_Where).second);
}
};

// if作用域 mapped_type()构造一个A类型的临时对象temp1, value_type构造一个pair类型的临时对象temp2, 
// if作用域退出时销毁temp1,销毁temp2时期内部second成员为A类型,析构函数被调用。
[解决办法]

mapped_type& operator[](const key_type& _Keyval)
{// find element matching _Keyval or insert with default mapped
iterator _Where = this->lower_bound(_Keyval);
if (_Where == this->end()

[解决办法]
 this->comp(_Keyval, this->_Key(_Where._Mynode())))
_Where = this->insert(_Where,
value_type(_Keyval, mapped_type()));
return ((*_Where).second);
}
};

[解决办法]
第一个次构造是你自己定义的A a1,第二次构造是map的[]操作符会利用默认构造函数产生一个pair的第二个元素,第一次析构是临时的A被析构。。。stl是值复制,因此在元素的转移过程中就会出现构造和析构,你应该写出默认复制构造函数和默认=操作符,这样构造和析构才是对称的,不然这样看起来回让人觉得只有析构没有构造。

热点排行