1

Is there any difference between these two other than their duration?

int ptr;
int *ptr = new int;

I understand the concept of pointers but I don't see a much of a use for for delcaring an int with a pointer.

Crally
  • 21
  • 3

2 Answers2

3

You use an object on the stack if you don't have the need for the object outside of the scope where it is created.

Example:

int foo(int in)
{
   int i = in + 2;
   return i;
}

i is not needed outside foo. Hence, you create an object on the stack and return its value.

You use an object on the heap if you have a need for the object outside the scope where it is created.

int* foo(int in)
{
   int* ip = new int(in + 2);
   return ip;
}

The pointer that ip points to is returned from foo and is expected to be used by the calling function. Hence, you need to create an object on the heap and return it.

That's the conceptual aspect of the difference. Normally, you won't need to use an object from the heap if you are talking about an int. The difference becomes important when you need to return an array.

int* foo()
{
   int arr[] = {1, 2, 3, 4};
   return arr;
}

That function will be a problem since it returns a pointer that will be invalid as soon as the function returns.

int* foo()
{
   int* arr = new int[4]{1, 2, 3, 4};
   return arr;
}

That will work since the returned pointer will point to valid objects even after the function returns. The calling function has to take responsibility to deallocate the memory though.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
-1

Difference can be seen from performance point of view.

Consider the worst case scenario:

int ptr; In this case all the required memory will be on the same page.

int *ptr = new int; In this case the address of ptr can be on one page and the memory which it points to can be on different page which may result in a page-fault while accessing the memory indirectly i.e *ptr.

sameerkn
  • 2,209
  • 1
  • 12
  • 13