简体   繁体   English

重定向指针会导致内存泄漏吗?

[英]Does redirecting a pointer introduce memory leak?

I have two pointers:我有两点建议:

int *a = new int;
int *b = new int;

Now I set b equal to a :现在我设置b等于a

b=a;

My concern is about the memory that b was initially pointing at.我担心的是b最初指向的内存。 When I redirect b to point to the memory that a points to and both point to the same memory location.当我重定向b为指向内存中a点,并都指向同一个内存位置。 What about the previous memory location of b, is it freed or it is in memory leak? b之前的内存位置呢,是被释放了还是内存泄漏了?

To prevent memory leak should I do it this way:为了防止内存泄漏,我应该这样做:

delete b;
b=a;

It's a leak.这是泄漏。

You should use smart pointers instead.您应该改用智能指针。

It's a memory leak.这是内存泄漏。 You didn't delete what you new -ed as b no longer points at the original location.你没有deletenew ed 因为b不再指向原始位置。 Try this:尝试这个:

int* a = new int;
int* b = new int;
int* originalb = b;
b = a;
delete originalb;
delete b; // or a

given that a and b remain the same.假设ab保持不变。
That being said prefer smart pointers , containers and RAII to raw pointers.话虽如此,与原始指针相比,更喜欢智能指针容器RAII

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

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