Search code examples
c++pointersvectordynamicallocation

C++ Dynamic Allocation with vectors and containers


1.What is the use of dynamic allocating vectors on the heap and is it a good practice?

2.What is the difference between the following:-

vector<Object> *col = new vector<Object>
 
vector<Object*> col

3.Does vectors dynamically allocate items on the heap in the following example:-

vector<Object> x;

or

vector<int> x;

Solution

  • You should almost always write vector<Object> or vector<int> (and maybe vector<vector<Object>>.

    Your other syntaxes (vector<Object>* and vector<Object*>) are often inappropriate in C++. See std::unique_ptr (or std::shared_ptr) for preferred alternatives.