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?
int** ppint = new int*;
*ppint = new int;
delete *ppint;
delete ppint;
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.
Yes, you can declare a pointer to a pointer... and yes, the pointer will be on the heap.
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.
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*;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With