Building default elements in vector

When reading the answers to this question , I had a doubt about the default construction of objects by default. To test this, 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, of course, the default constructor of the Test constructor is called when the vector object is created. But I can’t understand how STL initializes objects, am I creating a vector of a basic data type, such as an ints vector, since there is a default constructor for it? those. how do all ints in a vector have a value of 0? Isn't that trash?

+6
c ++ stl default-constructor built-in-types
source share
2 answers

It uses the default constructor equivalent for int, which is zero, initializing them. You can do it explicitly:

 int n = int(); 

sets n to zero.

Note that the default construct is only used and is required if the vector is set to its initial size. If you said:

 vector <X> v; 

there is no requirement that X have a default constructor.

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

The vector basically calls default for the type it points to: Type()

  • if it is a basic data type, such as int, double, then int (), double () {int () will get the value 0}
  • if the user data type then the default constructor will be called by default.
+1
source share

All Articles