We have code similar to the one below. We are trying to achieve RAII using a class called MemRelease class. Now, FXOMemRelease is being used the way shown in sample.cc.
Is this OK to use the obeject of FXOMemRelase like that ? Most of the time I see that the destructor for MemRelease only gets called after MakeString() is completed. That is fine.
Will it be the case always ? We got a memory issue and the truss output last pointed to the print statement in the MemRelease class.
MemRelease.cpp
template<typename T>
MemRelease<T>::MemRelease(T* store, unsigned char array_yesno, short release_yesno)
: ptr(store), array(array_yesno), release(release_yesno)
{
}
template<typename T>
T* MemRelease<T>::getStore()
{
return (ptr);
}
template<typename T>
MemRelease<T>::~MemRelease()
{
if (!release) return;
if ( (array == 'Y') || (array == 'y') )
{
cout << "deleting array in MemRelease pid = " << getpid() << endl;
delete [] ptr;
ptr = NULL;
}
else
{
cout << "deleting memory in MemRelease pid = " << getpid() << endl;
delete ptr;
ptr = NULL;
}
}
Sample.cc:
char* MakeString(char* str)
{
cout << "Entered MakeString\n";
char* newstr = new char[strlen(str) + 1];
strcpy(newstr, str);
return str;
}
int main()
{
char *str = new char[10];
strcpy(str, "jagan");
char* newstr = MakeString(MemRelease<char>(str).getStore());
getchar();
delete newstr;
}
Yes, always. The temporary object stays valid until the assignment to
newstrcompletes.As afriza points out, we can’t verify which destruction code is running because you haven’t included the default values for the constructor’s
array_yesnoandrelease_yesno. BTW, there’s a type calledboolwhich should be used for yes/no values.