c++: instantiate object [duplicate]

与世无争的帅哥 提交于 2019-12-11 01:31:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!