c – 调整容器大小时的奇怪行为
发布时间:2020-12-16 05:41:31 所属栏目:百科 来源:网络整理
导读:参见英文答案 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;};}
参见英文答案 >
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()); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |