Reputation: 371
Reading a lot about this well known problem I discovered and used the "Creation on first use", but it main problem is that it produces memory leaks.
Working a bit, I've done some light modification trying to solve that problem, and I got a solution:
1) Using a global static pointer instead a local static pointer
2) Using a separate function to delete the object.
Example:
static myObject* myObjectPtr=nullptr;
static myObjectDel() {delete myObjectPtr;}
inline myObject& myObjectRef()
{
if(myObjectPtr==nullptr)
{
myObjectPtr=new myObjectPtr;
atexit(myObjectDel);
}
return(*myObjectPtr);
}
So, I can ensure that:
1) The object is created before first use.
2) The object is deleted after last use.
3) There are no memory leaks.
It works with MS Visual Studio 2013 due the static pointer is zero-initialized at program startup, but I'm not sure if all compilers and operating systems does it.
In other words, Is it portable?
Thanks you and sorry for my poor english (I'm not english native)
Upvotes: 0
Views: 133
Reputation: 66371
Your solution is portable, but it's not thread-safe.
It's also needlessly complicated.
Don't use dynamic allocation:
inline myObject& myObjectRef()
{
static myObject theObject;
return theObject;
}
Leak-free (since the dawn of time) and thread-safe (since C++11).
Upvotes: 5
Reputation: 234655
I'd prefer static myObject* myObjectPtr;
since all static
pointers will be initialised to nullptr
anyway. The C++ standard guarantees that.
But your code is vulnerable to two threads calling inline myObject& myObjectRef()
for the first time which could lead to multiple new
to be balanced with only one delete
. You ought to use a mutex in that function to obviate that.
Upvotes: 1