Search code examples
c++dynamic-memory-allocation

Can I initialize a reference from the value of dereferencing the return of `new`?


As I've seen, new allocates an un-named object in the free store and returns a pointer to that un-named object.

So we can create a reference to that object:

int* pi = new int(100);
int& ri = *pi;

What interests me is I can create an object on the free store without assigning the return of new to a pointer, but to a reference to the un-named object through assigning the de-referenced value of new to the reference:

int& x = *(new int(7));

cout << x << endl; // 7
x += 34;
cout << x << endl; // 41

I want to know whether I can do this, or is it a bad idea?

N.B: In production, I keep away as much as possible from handling raw memory, I use smart pointers and STL containers instead.


Solution

  • I want to know whether I can do this or it is a bad idea?

    You can do this, but you really shouldn't. The reason is that it makes it harder to remember to deallocate the memory you received since you are no longer using a pointer. That gets you out of the pointer frame of mind and makes it easier to forget to have a call to delete on all exit paths.

    It is also going to look weird when you deallocate because you'd need to do something like

    delete &x;