【问题标题】:strange behavior when resize container [duplicate]调整容器大小时的奇怪行为[重复]
【发布时间】:2014-02-14 10:49:02
【问题描述】:

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

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

【问题讨论】:

  • 你有开启优化吗?我在 VS2013 中没有得到和你一样的结果。
  • @MohammedMajeed,没有优化,这是我的编译命令 g++ -Wall -o m main.cpp 。使用“g++ -Wall -O2 -o m main.cpp”会得到相同的结果。
  • @herohuyongtao 好像多出了一个,只好销毁了。
  • @camino 您的编译器或它附带的标准库似乎有问题。我在 ideone 上运行了你的代码,它运行良好。 ideone.com/7GJPbA
  • 看看here。我不认为它是重复的,但它很接近。

标签: c++ vector


【解决方案1】:

这是因为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());

【讨论】:

    【解决方案2】:

    在 C++11 之前,resize 有一个默认的第二个参数来提供初始化新元素的值:

    void resize(size_type sz, T c = T());
    

    这解释了为什么您会看到一个额外的对象被创建和销毁。

    在现代库中,这被替换为两个重载

    void resize(size_type sz);
    void resize(size_type sz, const T& c);
    

    所以你不应该看到任何额外的对象,除非你明确提供一个。在构建过程中,您还应该看到默认初始化,而不是复制初始化。

    【讨论】:

      【解决方案3】:

      您的vector::resize 实现可能会创建一个临时的默认初始化对象,即使在缩小规模时也是如此,因为它在扩大规模时使用它来初始化新元素。

      【讨论】:

      • 可能就是这种情况——否则它可能会调用CAT() 6 次,而不是CAT(const CAT&amp; c) 进行创建过程。运行构造函数时它可能会resize(int x)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多