0

code one:

vector<int> *intVector=new vector<int>();

code two:

vector<int> *intVector=new vector<int>;

code three:

vector<int> intVector();//compile error?

code four:

vector<int> intVector;  

my questions:

(1) is "vector intVector" call default constructor?
(2) when code 1 is similar with code 2, why code 3 compiled error?

4d4c
  • 8,049
  • 4
  • 24
  • 29
jiafu
  • 6,338
  • 12
  • 49
  • 73

1 Answers1

2

You ask:

(1) is "vector intVector" call default constructor?
(2) when code 1 is similar with code 2, why code 3 compiled error?

Regarding (1), yes, std::vector has a user-defined default constructor, which is used when no constructor arguments are provided.

Regarding (2), your code 3 shouldn't give an error of itself, but it is a declaration of a function, not a declaration of a variable. So if you're using it as a variable, then you may get compilation errors on that usage.

Your code example 4 is how you should generally use a std::vector. For a number of reasons there is little to no point in allocating a std::vector dynamically, with new, and there is a (relatively speaking) huge cost associated with new. So just use a straight std::vector object, and it takes care of memory allocation and deallocation for you.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331