c – 调整容器大小时的奇怪行为

参见英文答案 > Why has the std::vector::resize signature been changed in C++11?2
当调整向量的大小时,它将调用构造函数,然后将其破坏.
struct CAT
{
    CAT(){cout<<"CAT()"<<endl;}
    CAT(const CAT& c){cout<<"CAT(const CAT& c)"<<endl;};
    ~CAT(){cout<<"~CAT()"<<endl;};
};
int main()
{
    vector<CAT> vc(6);
    cout<<"-----------------"<<endl;
    vc.resize(3);
    cout<<"-----------------"<<endl;

}

输出

$./m 
CAT()
CAT(const CAT& c)
CAT(const CAT& c)
CAT(const CAT& c)
CAT(const CAT& c)
CAT(const CAT& c)
CAT(const CAT& c)
~CAT()
-----------------
CAT()          //why resize will call constructor?
~CAT()
~CAT()
~CAT()
~CAT()
-----------------
~CAT()
~CAT()
~CAT()

我使用ubuntu 13.10和gcc4.8

解决方法

这是因为resize的可选参数.

这是我在GCC 4.8中的实现:

void
  resize(size_type __new_size,value_type __x = value_type())
  {
if (__new_size > size())
  insert(end(),__new_size - size(),__x);
else if (__new_size < size())
  _M_erase_at_end(this->_M_impl._M_start + __new_size);
  }

仔细看看value_type __x = value_type().

http://www.cplusplus.com/reference/vector/vector/resize/

void resize (size_type n,value_type val = value_type());

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...