问题
Possible Duplicate:
C++ Object Instantiation vs Assignment
I am quite new to C++ and was wondering what is the difference(if any) between instantiating an object as
int main () {
vector< int > x(2);
}
or
int main () {
vector< int > x = vector< int > (2);
}
except for the fact that the latter takes longer to write. Thanks in advance!
回答1:
The difference is largely grammatical:
vector<int> x(2);
is direct initialization.vector<int> x = vector<int>(2);
is copy initialization.
The latter formally requires that the class have an accessible copy constructor, but in practice the copy will be elided and the two versions produce exactly the same code.
You should always prefer direct initialization.
You can also go insane:
vector<int> x = vector<int>(vector<int>(vector<int>(2)));
来源:https://stackoverflow.com/questions/12004115/c-instantiate-object