Does using references instead of pointers, resolve memory leaks in C++?(使用引用而不是指针是否可以解决 C++ 中的内存泄漏问题?)
问题描述
大多数内存泄漏发生在返回对象的指针而程序员忘记删除它时.
Most of memory leaks appear when a pointer of an object returned and programmer forgot to delete it.
例如:
class my_class
{
...
};
my_class* func1()
{
my_class* c = new my_class;
return c;
}
int main()
{
my_class* var1 = func1();
...
// Programmer forgot delete the var1: delete var1;
// -- or --
// Doesn't know 'delete[] var1;' is correct or 'delete var1;'.
}
当指向创建的对象的指针而程序员忘记删除它时,会出现一些内存泄漏.
Some of memory leaks appear when a pointer to an object created and programmer forgot to delete it.
例如:
class my_class
{
...
};
void func2(my_class* p)
{
...
}
int main()
{
my_class* var3 = new my_class;
func2(var3);
// Does func2 deletes var3? Programmer doesn't know.
// -- or --
// Programmer forgot delete the var3.
}
我使用了一种方法来解决内存泄漏,但在复杂情况下我不确定.
I use a method to resolve memory leaks but I don't sure about it in complex situations.
我的方法是:不使用任何指针(除了一处),只使用引用而不是指针.
例如:
class my_class
{
...
};
my_class& func1()
{
my_class* c = new my_class; // except one place.
return *c;
}
void func2(my_class& p)
{
...
}
int main()
{
my_class& var1 = func1();
my_class var2 = func1();
my_class var3;
func2(var3);
// There is nothing to forget.
}
使用引用而不是指针来解决内存泄漏问题吗?
Does using references instead of pointers, resolve memory leaks?
是解决内存泄漏的好方法还是有更好的方法?
Is it a good method for resolving memory leaks or there are better methods?
这个问题的一些答案不同意下面的代码没有内存泄漏.
Some answer of this question don't agree the below code don't have memory leak.
因为是新问题,所以单独问.
because it is a new question, I ask it seperately.
class my_class
{
...
};
my_class& func()
{
my_class* c = new my_class;
return *c;
}
int main()
{
my_class& var1 = func();
// I think there is no memory leak.
}
我在这里问:这段代码会泄漏内存吗?(引用,新建,但没有删除)
推荐答案
您还没有解决任何内存泄漏问题.如果你是新的,那么你必须删除.您所做的只是取消引用指针,它仍然需要删除.您可以通过创建本地对象并按值返回或使用智能指针来解决内存泄漏问题.100 次中有 99 次,我更喜欢按价值回报选项.
You haven't resolved any memory leaks. If you new, then you must delete. All you did was dereference the pointer, it still needs to be deleted. You can resolve memory leaks by creating local objects and returning by value, or using smart pointers. 99 times out of 100, I prefer the return by value option.
现在,像许多初学者一样,按值返回大型对象的想法可能会吓到您以性能为中心的头脑.阅读这篇以减轻您的恐惧.
Now, like many beginners, the idea of returning large objects by value probably scares your perf-centric mind. Read this to allay your fears.
这篇关于使用引用而不是指针是否可以解决 C++ 中的内存泄漏问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用引用而不是指针是否可以解决 C++ 中的内存泄漏问题?
基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01