I have noticed something very weird yesterday.
After trying to locate where my program was crashing from, I discovered it was happening from my Error class. that was humouros. I was returning my error info as a const reference which I thought would bind.
Now, realizing the temporary wouldnt bind, I decided to return my error info as manual dynamic memory; using a ctor and dtor to "delete" the memory.
Thd WEIRD part is that I still got crash and the reason was; my destructor was getting called INDEFINITELY;
// error.h
struct ErrorInfo {};
template <class T>
const ErrorInfo& error(const T&);
// Found.h
struct Found
{
const char *begin, *end;
};
Found find(const char*,const char*);
struct Found_ErrorInfo : ErrorInfo
{
const char *type;
char fault[3];
unsigned index;
Found_ErrorInfo()
: type("Not found"), fault{'\e','w',0}, index(0) {};
~Found_ErrorInfo { delete this; }
};
template <>
const ErrorInfo& error<Found>(const Found &f)
{
return *new Found_ErrorInfo();
}
// main.cpp
int main()
{
Found f = find("dada", "I love my mama");
if(f.begin != nullptr) std::cout << f.begin;
else const ErrorInfo &info = error(f);
}
As you can see from the sample, I return a dynamically allocated error info from the error function specialized for struct found. I then have a destructor of type Found_ErrorInfo to delete this dynamic memory/ delete itself. What happens nexg is the delete operator calls the same destructor, which again calls the delete operator and the cycle continues.
My question is, What is ths purpose of the delete operator? Is it to inform the OS that we no longer need the memory? Or just to call the destructor and then the destructor informs the OS to take back the memory.
Aucun commentaire:
Enregistrer un commentaire