Possible Duplicate:
deleting memory allocated in static function in C++
Hi All,
I have C++ class as follows
interface myInterface;
class anotherClass : public myInterface {};
class myClass {
private:
myClass() {}
~myClass() {}
typedef std::map<string, myInterface* > stringToClass;
static stringToClass s_stringToClass;
public:
static myInterface& getStringToclass(string name);
};
in above class for getStringToClass defintion is as follows
myInterface& myClass::getStringToClass(string name) {
stringToClass::iterator iter;
iter = s_stringToClass.find(name);
if(iter == s_stringToClass.end()) {
typedef stringToClass::value_type stringToClassPair;
anotherClass* pothClass = new anotherClass();
s_stringToClass.insert(stringToClassPair(name, pothClass));
return pothClass;
}
else {
return iter->second;
}
}
now my question is we are allocating memory in static function and returning a pointer of class type, but here i want to retrun a reference as we don’t want to give control of pointer to user. And also i don’t want to delete immedetily unless user asked to or want to delete at end of program How can we delete memory? As there is only instance of class will be there, as there are only static functions.
Thanks for the help.
Note:
You should reformat on the old thread, instead of creating new question. Anyway, I paste my answer here.
I think in your case, the destructor won’t help, because there is no any object of MyClass.
I propose three ways
1. Don’t store pointer, store the object itself.
2. Put the delete function into atexit; In your case
Though I put a lot in second way, I suggest the 3rd way.