Default construction of elements in a vector

廉价感情. 提交于 2019-12-10 13:32:43

问题


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?


回答1:


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

int n = int();

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:

vector <X> v;

there is no requirement that X have a default constructor.




回答2:


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()

  • if it is basic data type like int, double are there then int(), double() { int() will get value 0}
  • if the user defined data type then default constructor would be called.


来源:https://stackoverflow.com/questions/877699/default-construction-of-elements-in-a-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!