views:

640

answers:

5

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?

+26  A: 
int** ppint = new int*;
*ppint = new int;

delete *ppint;
delete ppint;
AraK
+5  A: 

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

jsight
+6  A: 

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.

Tamás Szelei
+2  A: 

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*;
David Thornley
+1  A: 

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.

Zeroshade