向量中元素的默认构造
在阅读这个问题的答案时,我对向量中对象的默认构造有疑问。 为了测试它,我编写了以下测试代码:
struct Test
{
int m_n;
Test();
Test(const Test& t);
Test& operator=(const Test& t);
};
Test::Test() : m_n(0)
{
}
Test::Test(const Test& t)
{
m_n = t.m_n;
}
Test& Test::operator =(const Test& t)
{
m_n = t.m_n;
return *this;
}
int main(int argc,char *argv[])
{
std::vector<Test> a(10);
for(int i = 0; i < a.size(); ++i)
{
cout<<a[i].m_n<<"\n";
}
return 0;
}
果然,在创建向量对象时调用了 Test structs 默认构造函数。 但我无法理解的是,STL 如何初始化我创建基本数据类型向量(例如整数向量)的对象,因为它有默认构造函数? 即向量中的所有整数的值如何均为 0? 不应该是垃圾吗?
While reading the answers to this question I got a doubt regarding the default construction of the objects in the vector. To test it I wrote the following test code:
struct Test
{
int m_n;
Test();
Test(const Test& t);
Test& operator=(const Test& t);
};
Test::Test() : m_n(0)
{
}
Test::Test(const Test& t)
{
m_n = t.m_n;
}
Test& Test::operator =(const Test& t)
{
m_n = t.m_n;
return *this;
}
int main(int argc,char *argv[])
{
std::vector<Test> a(10);
for(int i = 0; i < a.size(); ++i)
{
cout<<a[i].m_n<<"\n";
}
return 0;
}
And sure enough, the Test structs default constructor is called while creating the vector object. But what I am not able to understand is how does the STL initialize the objects I create a vector of basic datatype such as vector of ints since there is default constructor for it? i.e. how does all the ints in the vector have value 0? shouldn't it be garbage?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它使用与 int 的默认构造函数等效的功能,即对它们进行零初始化。 您可以明确地执行此操作:
将 n 设置为零。
请注意,只有在给定向量初始大小的情况下才使用和需要默认构造。 如果你说:
不要求X有默认构造函数。
It uses the equivalent of the default constructor for ints, which is to zero initialise them. You can do it explicitly:
will set n to zero.
Note that default construction is only used and required if the vector is given an initial size. If you said:
there is no requirement that X have a default constructor.
Vector 基本上会为其指向的类型调用
default
:Type()
,double 则存在 int(), double() { int() 将获取值 0}
将调用默认构造函数。
Vector basically calls
default
for the type to which it points:Type()
double are there then int(), double() { int() will get value 0}
default constructor would be called.