矢量中元素的默认结构

矢量中元素的默认结构

本文介绍了矢量中元素的默认结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读此问题的答案时, a>我对向量中对象的默认构造有疑问。要测试它,我写了以下测试代码:

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;
}

当然,Test structs默认构造函数在创建向量对象。但是我不能理解的是STL如何初始化对象我创建一个基本的数据类型的向量,如ints的向量,因为有默认的构造函数?即向量中的所有int如何具有值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?

推荐答案

它使用相当于ints的默认构造函数,这是零初始化它们。你可以明确地做:

It uses the equivalent of the default constructor for ints, which is to zero initialise them. You can do it explicitly:

int n = int();

会将n设为零。

注意,如果向量被赋予初始大小,则仅使用并且需要默认构造。如果您说:

Note that default construction is only used and required if the vector is given an initial size. If you said:

vector <X> v;

没有要求X具有默认构造函数。

there is no requirement that X have a default constructor.

这篇关于矢量中元素的默认结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!