In contexts, there may be a difference in std::initializer_list<> , for example:
Case 1 - () and {}
#include <initializer_list> #include <iostream> using namespace std; struct Test2 { Test2(initializer_list<int> l) {} }; int main() { Test2* test3 = new Test2(); // compile error: no default ctor Test2* test4 = new Test2{}; // calls initializer_list ctor }
Case 2: (v) and {v}
struct Value { }; struct Test3 { Test3(Value v) {} Test3(initializer_list<Value> v) {} }; int main() { Value v; Test3* test5 = new Test3(v);
As stated by Meyers and others, there is also a huge difference when using STL:
using Vec = std::vector<int>; Vec* v1 = new Vec(10);
and not limited to std::vector only
In this case, the difference does not exist (and initializer_list ctor is ignored)
#include <initializer_list> #include <iostream> using namespace std; struct Test { Test() {} Test(initializer_list<int> l) {} }; int main() { Test* test1 = new Test(); // calls default ctor Test* test2 = new Test{}; // same, calls default ctor }
There is also a known difference in this case.
void f() { Test test{}; Test test2(); }
where test is the default initialized object of type test , and test2 is the function declaration.
Peter K
source share