简体   繁体   中英

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?

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

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;

Yes, you can. But I would consider it a bad idea. Once this reference goes out of scope, you have no way of freeing the dynamic memory, (or you simply forget, that it's dynamic memory in disguise) which will most likely cause a memory leak.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM