Difference between `vector v;` and `vector v = vector();`

Starting from C++17 there’s no difference whatsoever.

There’s one niche use case where the std::vector = std::vector initialization syntax is quite useful (albeit not for default construction): when one wants to supply a “count, value” initializer for std::vector<int> member of a class directly in the class’s definition:

struct S {
  std::vector<int> v; // Want to supply `(5, 42)` initializer here. How?
};

In-class initializers support only = or {} syntax, meaning that we cannot just say

struct S {
  std::vector<int> v(5, 42); // Error
};

If we use

struct S {
  std::vector<int> v{ 5, 42 }; // or = { 5, 42 }
};

the compiler will interpret it as a list of values instead of “count, value” pair, which is not what we want.

So, one proper way to do it is

struct S {
  std::vector<int> v = std::vector(5, 42);
};

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)