2

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!

Community
  • 1
  • 1
linuxfever
  • 3,763
  • 2
  • 19
  • 43

1 Answers1

7

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)));
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • +1 Was to fast for me there. Might add that the direct initialization should be added to prevent invocation of an copy constructor that cannot be elided. – daramarak Aug 17 '12 at 10:38