Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you declare a pointer on the heap?

This is the method for creating a variable on the heap in C++:

T *ptr = new T;

ptr refers to a pointer to the new T, obviously. My question is, can you do this:

T *ptr = new T*;

That seems like it could lead to some very, very dangerous code. Does anyone know if this is possible/how to use it properly?

like image 743
jkeys Avatar asked Aug 13 '09 20:08

jkeys


5 Answers

int** ppint = new int*;
*ppint = new int;

delete *ppint;
delete ppint;
like image 185
Khaled Alshaya Avatar answered Oct 16 '22 15:10

Khaled Alshaya


new T* returns a pointer to a pointer to a T. So the declaration is not correct, it should be:

T** ptr = new T*;

And it will reside on the heap.

like image 7
Tamás Szelei Avatar answered Oct 16 '22 14:10

Tamás Szelei


Yes, you can declare a pointer to a pointer... and yes, the pointer will be on the heap.

like image 4
jsight Avatar answered Oct 16 '22 15:10

jsight


It was mentioned as why you might need something like this. The thing that comes to mind is a dynamic array. (Most vector implementations use this actually.)

// Create array of pointers to object
int start = 10;
SomeObject** dynamic = new SomeObject*[start];
// stuff happens and it gets filled
// we need it to be bigger
{
    SomeObject** tmp = new SomeObject*[start * 2];
    for (size_t x = 0; x < start; ++x)
        tmp[x] = dynamic[x];
    delete [] dynamic;
    dynamic = tmp;
}
// now our dynamic array is twice the size

As a result, we copy a bunch of pointers to increase our array, not the objects themselves.

like image 4
Zeroshade Avatar answered Oct 16 '22 14:10

Zeroshade


You can't do

T *ptr = new T*;

since the return type of new foo is "pointer to foo" or foo *.

You can do

T **ptr = new T*;
like image 2
David Thornley Avatar answered Oct 16 '22 15:10

David Thornley