Creating Vector of Unique Pointers in C++

To create vectors of unique pointers in C++, we can first define the vector of type unique_ptr of the desired type and then use the std::make_unique defined inside <memory> header file that to create a unique_ptr object, which is a smart pointer that manages the lifetime of dynamically allocated objects.

Syntax to Create Vectors of Unique Pointers in C++

vector<unique_ptr<Type>> myVector;

Here,

  • Type is the type of objects that the unique pointers will point to.
  • constructor_arguments are optional arguments that are passed to the constructor of the object being created.

C++ Program to Create Vectors of Unique Pointers

The below program demonstrates how we can create a vector of unique pointers in C++.

C++




// C++ Program to illustrate how to create vectors of unique
// pointers
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
  
// Creating a class MyClass
class MyClass {
public:
    // Constructor that takes two integers as parameters
    MyClass(int num1, int num2): num1(num1), num2(num2){}
  
    // Function to compute the sum of num1 and num2
    int sum() const { return num1 + num2; }
  
private:
    // Private data members num1 and num2
    int num1;
    int num2;
};
  
int main()
{
    // Declaring a vector of unique pointers to MyClass
    // objects
    vector<unique_ptr<MyClass> > myVector;
  
    // Allocate objects and store them in the vector
    myVector.push_back(make_unique<MyClass>(5, 10));
    myVector.push_back(make_unique<MyClass>(8, 3));
  
    // Accessing the first object in the vector and
    // computing its sum
    cout << "Sum of first object: " << myVector[0]->sum()
         << endl;
  
    // Iterating over the vector and computing the sum of
    // each object
    for (auto& ptr : myVector) {
        cout << "Sum: " << ptr->sum() << endl;
    }
  
    return 0;
}


Output

Sum of first object: 15
Sum: 15
Sum: 11

Time Complexity: O(N), where N is the size of the vector.
Auxilliary Space: O(N)



How to Create Vectors of Unique Pointers in C++?

In C++, the vector is defined as a dynamic array that can grow or shrink in size. Vectors of unique pointers are commonly used to manage the collections of dynamically allocated objects as they combine the dynamic resizing capability of vectors with the automatic memory management provided by unique pointers. In this article, we will learn to create vectors of unique pointers in C++.

Similar Reads

Creating Vector of Unique Pointers in C++

To create vectors of unique pointers in C++, we can first define the vector of type unique_ptr of the desired type and then use the std::make_unique defined inside header file that to create a unique_ptr object, which is a smart pointer that manages the lifetime of dynamically allocated objects....