Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nulling pointers defined within function

Tags:

c++

c++11

In the codebase I inherited, I notice that the previous coder would null pointers init'ed within the function before the function closes.

Something like:

void MainClass::run() {

MyClass* _classPtr = GetClassPtr(); // Assume no problems here.

// do stuff to _classPtr

_classPtr = nullptr; // Is this even necessary?

return;
}

I find it unnecessary since the pointer's memory (Not the object itself, just the pointer) should be freed up at function close. Is that true?

like image 729
Mark Ang Avatar asked Jul 26 '26 10:07

Mark Ang


1 Answers

It's not necessary to do this. When the function goes out of scope the the memory used by the pointer will be release regardless of what it's set to. However, the object pointed to will not be released.

This is probably just a coding standard adopted by the previous developer.

like image 162
Sean Avatar answered Jul 27 '26 22:07

Sean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!