Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use an empty {} to initialize a vector is different?

Tags:

c++

stl

I see some people tend to initialize a vector with an empty {}, and I wonder whether it is different from directly initialize with the default constructor?

for example:

#include <vector>
#include <iostream>
using namespace std;

int main()
{
    vector<int> vec;
    vector<int> vec2 {};

    cout << sizeof(vec) << " " << sizeof(vec2) << endl; // 24 24
    cout << vec.size() << " " << vec2.size() << endl;   // 0 0 
}

and I check its assembly code, and it shows that initializing a vector with an empty {} generate more code(https://godbolt.org/z/2BAWU_).

Assembly code screen shot here

I am quite new to C++ language, and I would be grateful if someone could help me out.

like image 775
Vince Lim Avatar asked Sep 12 '25 09:09

Vince Lim


1 Answers

Using braces is value initialization. Not using them is default initialization. As somebody alluded to in the comments, they should generate the exact same code when optimizations are turned on for vector. There's a notable difference with built-in types like pointers and int; there default initialization does nothing, while value initialization sets them to nullptr and zero, respectively.

like image 50
Zuodian Hu Avatar answered Sep 14 '25 23:09

Zuodian Hu