简体   繁体   English

我可以从取消引用`new`的返回值初始化引用吗?

[英]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.正如我所见, new在空闲存储区中分配了一个未命名的 object 并返回一个指向该未命名的 object 的指针。

So we can create a reference to that object:所以我们可以创建一个对 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:我感兴趣的是我可以在免费存储上创建 object 而不将new的返回分配给指针,而是通过将取消引用的new值分配给引用来引用未命名的 object :

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.注意:在生产中,我尽可能避免处理原始 memory,而是使用智能指针和 STL 容器。

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.原因是因为不再使用指针,所以更难记住释放收到的 memory。 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.这使您摆脱了指针框架,并且更容易忘记在所有退出路径上调用delete

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. 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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