调整向量大小时,它将调用构造函数,然后销毁它。
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
发布于 2014-01-23 18:07:53
这是因为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());发布于 2014-01-23 18:34:47
在C++11之前,resize有一个默认的第二个参数来提供初始化新元素的值:
void resize(size_type sz, T c = T());这就解释了为什么你会看到一个额外的物体被创建和破坏。
在现代图书馆中,这将被两个重载所取代。
void resize(size_type sz);
void resize(size_type sz, const T& c);因此,除非显式地提供对象,否则不应该看到任何额外的对象。您还应该看到默认初始化,而不是复制初始化,在建设期间。
发布于 2014-01-23 18:03:31
即使在缩小规模时,vector::resize的实现也可能创建一个临时的默认初始化对象,因为它在升级时使用它初始化新元素。
https://stackoverflow.com/questions/21315791
复制相似问题