Dynamically Allocating Arrays with Smart Pointers

How do I dynamically allocate an array with smart pointers?

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.

Smart Pointers and std::unique_ptr

An introduction to memory ownership using smart pointers and std::unique_ptr in C++

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Mixing Smart and Raw Pointers
Is it okay to mix smart pointers and raw pointers in the same program?
Should I Pass Smart Pointers by Reference?
Should I pass smart pointers by value or reference?
Using Smart Pointers with Custom Deleters
Can I use smart pointers with my own custom deleters?
std::make_unique vs new Keyword
What are the advantages of using std::make_unique over the new keyword?
Using std::move with std::unique_ptr
What does std::move do when used with std::unique_ptr?
Using std::unique_ptr as a Class Member
How do I use std::unique_ptr as a member of a class?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant