涉及的上下文可能存在差异std::initializer_list<>
, e.g.:
情况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); // calls Test3(Value)
Test3* test6 = new Test3{v}; // calls Test3(initializer_list<Value>)
}
正如 Meyers 和其他人所说,使用 STL 时也存在巨大差异:
using Vec = std::vector<int>;
Vec* v1 = new Vec(10); // vector of size 10 holding 10 zeroes
Vec* v2 = new Vec{10}; // vector of size 1 holding int 10
并且它不限于std::vector
only
在这种情况下,虽然没有区别(并且initializer_list
ctor 被忽略)
#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
}
在这种情况下还有一个众所周知的区别
void f() {
Test test{};
Test test2();
}
where test
是类型的默认初始化对象Test
and test2
是一个函数声明。