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

标签 c++ vector

<分区>

当调整 vector 大小时,它会调用构造函数然后销毁它。

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++ - 调整容器大小时的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21315791/

相关文章:

c++ - 如何从由 google HEAPPROFILER 创建的 .heap 文件生成图表

C++ 将一个 vector append 到另一个 vector

c++ - 库达 CMake : undefined reference

c++ - 在 vector c++ 中显示运行时断言错误

c++ - 如何使用 lambda 删除空 vector 单元格?

python - 在 python 中生成陆地多边形

c++ - 关于CMake

C++多态指针不能调用成员函数

c++ - 使用 .size() 与 const 变量进行循环

c++ - 使用 ostream_iterator 和运算符 << 显示指针 vector