您的位置:首页 > 其它

vector test(4)为什么会调用type的默认构造

2010-05-21 23:59 387 查看
/*作者:帅得不敢出门

*出处:C++爱好者灌水天堂 群号3503799

*/

问题出自群里,vector<type> test(4)为什么会调用type的默认构造,调用4次挎贝构造不就结了?

分析如下

调试过程 从1开始 看//注释后面标号

vector<type> test(4)为什么会调用type的默认构造

#include <stdio.h>
#include <stdlib.h>
#include <vector>
using namespace std;

class A{
public:
A(const A& a){printf("A(A&)/n");}
A(){printf("A()/n");} //3. b--------- f10 跳到a
};
int main(void)
{
vector<A> test(4); //首先1. f5 f11 跑到a
return 0;
}
A() //问题在这里 为什么会调用到默认构造
A(A&)
A(A&)
A(A&)
A(A&)
过程分析
默认构造生成一个对象
然后4个A类元素都拷贝自它

explicit vector(size_type _Count)
: _Mybase()
{ // construct from _Count * _Ty()
/*a-----*/ _Construct_n(_Count, _Ty());//2. f10 跑到b 4.从3重新跑到这里再f11跑到c
}
相应值情况: 名称 值 类型
- _Alval {...} std::allocator<A>
std::_Allocator_base<A> {...} std::_Allocator_base<A>
_Count 4 unsigned int
this [0]() std::vector<A,std::allocator<A> > * const
--------------------------------------------------------
5.
/*c----------------*/
此时
参数情况:
_Val {...} const A & 这个是由默认构造产生的
void _Construct_n(size_type _Count, const _Ty& _Val)
{ // construct from _Count * _Val
if (_Buy(_Count))
{ // nonzero, fill it
_TRY_BEGIN
_Mylast = _Ufill(_Myfirst, _Count, _Val); // copy initializing _Count * _Val, using

allocator这里调用了_Count次拷贝构造函数
_CATCH_ALL
_Tidy();
_RERAISE;
_CATCH_END
}
}

环境:vs2005
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐