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

Viewed 56

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.

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.

Related