这会导致C ++的内存泄漏吗? [英] Will this lead to a memory leak in C++?

查看:149
本文介绍了这会导致C ++的内存泄漏吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++内存管理的怀疑,这是(显然)与引用和指针相关。假设我有一个类,方法 my_method

I have a C++ memory management doubt, that's (obviously) related to references and pointers. Suppose I have a class Class with a method my_method:

OtherClass& Class::my_method( ... ) {
    OtherClass* other_object = new OtherClass( ... );
    return *other_object;
}

同时在附近的一段代码中:

Meanwhile in a nearby piece of code:

{
    Class m( ... );
    OtherClass n;
    n = m.my_method( ... );
}



因此,我知道有一个关于指针的通用规则-ed,must be delete-d),以避免内存泄漏。但基本上我引用了我的堆分配的对象,所以当n超出范围,不应该调用其他类的析构函数,从而释放以前由other_object指向的内存?
所以到底真正的问题是:这会导致内存泄漏吗?

So, I know that there's a general rule about pointers (~ "anything new-ed, must be delete-d") to avoid memory leaks. But basicly I'm taking a reference to my heap-allocated object, so when n goes out of scope, shouldn't the destructor of OtherClass be called thus freeing the memory previously pointed by other_object? So in the end the real question is: will this lead to a memory leak?

谢谢。

推荐答案

很明显,你想返回一个新的对象给调用者,你不需要保留任何引用。为此,最简单的做法是按值返回对象。

It's fairly obvious that you want to return a new object to the caller that you do not need to keep any reference to. For this purpose, the simplest thing to do is to return the object by value.

OtherClass Class::my_method( ... ) {
    return OtherClass( ... );
}

然后在调用代码中可以这样构造新对象。 p>

Then in the calling code you can construct the new object like this.

{
    Class m( ... );
    OtherClass n( m.mymethod( ... ) );
}

这避免了任何关于返回对临时表的引用或要求客户端管理器删除的返回指针。注意,这确实需要您的对象是可复制的,但它是一个法律和通常实现的优化,以避免在按值返回时复制。

This avoids any worries about returning reference to temporaries or requiring the client to manager deletion of a returned pointer. Note, that this does require your object to be copyable, but it is a legal and commonly implemented optimization for the copy to be avoided when returning by value.

需要考虑一个共享指针或类似的,如果你需要共享所有权或对象的生命超出调用函数的范围。在后一种情况下,您可以将此决定留给客户,并仍然按值返回。

You would only need to consider a shared pointer or similar if you need shared ownership or for the object to have a lifetime outside the scope of the calling function. In this latter case you can leave this decision up to the client and still return by value.

例如

{
    Class m( ... );

    // Trust me I know what I'm doing, I'll delete this object later...
    OtherClass* n = new OtherClass( m.mymethod( ... ) );
}

这篇关于这会导致C ++的内存泄漏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆