1

I have a class variable ptr, I want it to point to the first element of my 1D int array.

What is the difference between these two statements, and which one should I use?

shared_ptr<int> ptr1;
shared_ptr<int[]> ptr2;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
heyloo
  • 35
  • 3
  • Do you know what `[]` usually implies for a variable? And if the array already exists, do you know what is implied by using a smart pointer? – sweenish Jan 24 '23 at 16:21

1 Answers1

4

shared_ptr<int> holds an int* pointer to a single int. That int is expected to be allocated with the new operator (preferably via a call to std::make_shared<int>(value)), and will be freed with the delete operator.

shared_ptr<int[]> holds an int* pointer to the 1st element of an int[] array. That array is expected to be allocated with the new[] operator (preferably via a call to std::make_shared<int[]>(size)), and will be freed with the delete[] operator.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770