patterncppMinor
Overloading the new operator
Viewed 0 times
theoverloadingnewoperator
Problem
This may be a naive question, but what are the dangers of the following code (allocate more memory in the new operator for the info struct)?
struct Info
{
Info():nLineNo(0){memset(cFile, 0, 256);}
~Info(){}
char cFile[256];
unsigned int nLineNo;
};
void *operator new(size_t Size, const char *pcFile, const unsigned int nLine)
{
Info *pData = 0;
pData = (Info*)malloc(Size + sizeof(Info));
strcpy(pData->cFile, pcFile);
pData->nLineNo = nLine;
return (void*)pData;
}
void operator delete(void *pData)
{
Info *pInfo = (Info*)pData;
// could use pInfo->nLineNo to check for it within hash table of allocated blocks - just an example
free(pData);
}Solution
You are not overloading the new operator correctly.
See: How should I write ISO C++ Standard conformant custom new and delete operators?
But you should not be overloading new at all.
All the work you are doing here is stuff that goes in the constructor.
The sole job of the new operator is to allocate memory (not initialize it).
As a side note:
Though you can actually add parameters to new.
Doing so is not a good idea.
As it is not normal, and thus makes it harder to maintain.
The code above will be called if you do:
See: How should I write ISO C++ Standard conformant custom new and delete operators?
But you should not be overloading new at all.
All the work you are doing here is stuff that goes in the constructor.
The sole job of the new operator is to allocate memory (not initialize it).
As a side note:
Though you can actually add parameters to new.
Doing so is not a good idea.
As it is not normal, and thus makes it harder to maintain.
The code above will be called if you do:
// Note: The first parameter (ie size) will be auto inserted as the first parameter.
Info* data = new ("File Name", 12) Info;Code Snippets
// Note: The first parameter (ie size) will be auto inserted as the first parameter.
Info* data = new ("File Name", 12) Info;Context
StackExchange Code Review Q#4412, answer score: 3
Revisions (0)
No revisions yet.