Search code examples
c++initialization

C++ vector initialization?


Possible Duplicate:
Do the parentheses after the type name make a difference with new?
What do the following phrases mean in C++: zero-, default- and value-initialization?

I've used vector without any problem but i still have a question about it. I always use code like this,

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

so, can i use:

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

I know what () does, but whats the difference? In v1, does vector ever initialize any integer?


Solution

  • First your question: new calls the default constructor, you don't need to do this "manually". But then: Try to use value types as often as possible in C++. They are not only faster, but also easier and safer, because the destructor gets automaticly called when leaving the scope. So just write

    std::vector<int> v; // Calls default constructor
    

    If you really need the heap, try using smart pointers such as shared_ptr and unique_ptr, this way you can't forget to call delete. (And delete also calls the destructor, no need to do this manually.)