Smart Pointers and std::unique_ptr

Dynamically Allocating Arrays with Smart Pointers

How do I dynamically allocate an array with smart pointers?

Illustration representing computer hardware

To dynamically allocate an array with a smart pointer, you can use std::unique_ptr with an array type:

#include <memory>
#include <iostream>

int main() {
  std::unique_ptr<int[]> Array{new int[5]{
    1, 2, 3, 4, 5}};

  for (int i = 0; i < 5; i++) {
    std::cout << Array[i] << ' ';
  }
}
1 2 3 4 5

Note that we use int[] as the template argument to std::unique_ptr, not just int. This tells the smart pointer that it's managing an array, not a single object.

When the unique_ptr goes out of scope, it will automatically call delete[] on the managed array.

If you need to specify the size of the array at runtime, you can use std::make_unique:

#include <memory>
#include <iostream>

int main() {
  int size{5};
  std::unique_ptr<int[]> Array{
    std::make_unique<int[]>(size)};

  for (int i = 0; i < size; i++) {
    Array[i] = i + 1;
    std::cout << Array[i] << ' ';
  }
}
1 2 3 4 5

Note that when using std::make_unique, we don't use the new keyword.

Also remember that std::unique_ptr<int[]> does not keep track of the size of the array. You need to track that separately if needed.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved