简体   繁体   English

向量中元素的默认构造

[英]Default construction of elements in a vector

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. 当然,在创建矢量对象时会调用Test结构默认构造函数。 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? 但是我无法理解的是STL如何初始化对象我创建了一个基本数据类型的向量,例如int的向量,因为它有默认的构造函数? ie how does all the ints in the vector have value 0? 即向量中的所有整数如何具有值0? shouldn't it be garbage? 不应该是垃圾吗?

It uses the equivalent of the default constructor for ints, which is to zero initialise them. 它使用了int的默认构造函数的等价物,即零初始化它们。 You can do it explicitly: 你可以明确地做到:

int n = int();

will set n to zero. 将n设置为零。

Note that default construction is only used and required if the vector is given an initial size. 请注意,仅当向量具有初始大小时,才使用默认构造并且必需。 If you said: 如果你说:

vector <X> v;

there is no requirement that X have a default constructor. 不要求X具有默认构造函数。

std::vector<Type> a(10);        // T could be userdefined or basic data type

Vector basically calls default for the type to which it points: Type() Vector基本上调用它指向的类型的defaultType()

  • if it is basic data type like int, double are there then int(), double() { int() will get value 0} 如果它是像int这样的基本数据类型,那么double就是int(),double(){int()将得到值0}
  • if the user defined data type then default constructor would be called. 如果用户定义了数据类型,那么将调用默认构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM