问题描述
大多数内存泄漏发生在返回对象的指针而程序员忘记删除它时.
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++ 中的内存泄漏问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!