Will this lead to a memory leak in C++?

2019-06-20 04:37发布

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( ... );
}

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?

Thanks.

7条回答
2楼-- · 2019-06-20 05:28

Calling the destructor and freeing the memory are two distinct things in C++.

delete does both call the destructor and free the memory. delete[] calls the destructor for the allocated number of elements, then frees the memory.

When OtherClass goes out of scope, the destructor is called, but the memory is not freed.


As a suggestion, when you feel you have thoroughly understood pointers in C++, look into smart pointers, e.g. boost smart pointers to ease your memory management life in C++. (e.g. see the article here for an introduction)

查看更多
登录 后发表回答