有可能在環境中的差異涉及std::initializer_list<>
,如:
案例1 - ()
和{}
#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
}
案例2:(v)
和{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>)
}
正如邁爾斯陳述,並使用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
只有
在這種情況下沒有差別,但(和initializer_list
構造函數被忽略)
#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();
}
其中test
是類型的默認初始化對象Test
和test2
是一個函數聲明。
我固定您的標題的術語問題。 –