Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static initialization and smart pointers

Tags:

c++

Is this function guaranteed not to create any memory leaks (there is no additional allocation in SomeObject):

void FreeFunction()
{
   static boost::scoped_ptr<SomeObject> MyStaticObject(new SomeObject);
}

I never used the combination of static allocation and a smart pointer. It seems to work fine with my compiler, but I would like to know if this always cleans up the allocated memory.

like image 244
nabulke Avatar asked Jun 13 '26 15:06

nabulke


1 Answers

Yes, there is no memory leak.
The static here means that the variable MyStaticObject is initialized on first call to FreeFunction() and then it stays alive throughout the lifetime of the program(just like any other static variable would).
The C++ run-time arranges and makes sure that MyStaticObject is destroyed at some point.

like image 139
Alok Save Avatar answered Jun 16 '26 06:06

Alok Save



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!