Consider this code:
#include <iostream>
using namespace std;
struct SOME_OTHER_BASE {
// members
};
struct FOO : SOME_OTHER_BASE {
int value;
static FOO *CreatePtr(int param)
{
FOO *res = new FOO();
res->value = param;
return res;
}
static FOO &CreateRef(int param)
{
return *CreatePtr(param);
}
};
int main() {
FOO *ptr = FOO::CreatePtr(2);
FOO &ref = FOO::CreateRef(4);
FOO local = FOO::CreateRef(5);
cout << "ptr: " << ptr->value << endl;
cout << "ref: " << ref.value << endl;
cout << "local: " << local.value << endl;
delete ptr;
delete &ref;
return 0;
Requirements:
- FOO::CreatePtr method may return NULL under some circumstances (allocation failed and was handled, invalid parameters, etc.)
- FOO is POD, but not an aggregate
What I want: as few as possible delete calls (and memory leaks).
My observations:
- I can use FOO::CreatePtr, check for
NULL
and alwaysdelete
afterwards - I can use FOO::CreateRef, but then I can't really check for null and I still have to
delete
- I could make
FOO::CreateRef
return a special instance whenCreatePtr
wasNULL
. That would help with NULL checking, but still not with deleting.
- I could make
- I could use the local variant, but I think I have a memory leak right there (the
CreatePtr(5)
never gets deleted, only copied intolocal
)- This is highly ineffective because there's an unnecessary alloc and a copy
- I can't use brace initialization because FOO is not an aggregate
Is there any way I could declare a local variable of FOO type and initialize it within declaration such that it would automatically get deleted on function exit?