Re: Never returning a NULL pointer
On Mar 23, 8:01 am, ZikO <ze...@op.pl> wrote:
Suraj wrote:
Its possible that the allocation failed, Its OK for me. Now throughout
the code i need to check for (ptr!=NULL) before using it.
I want to avoid this.
The alternative way is for example, if it's ok for you, trying to catch
the exception bad_alloc which new throws if allocation is unsuccessful.
struct A {
// ....
}
A* GetPointer() {
return new A;
}
int main() {
try {
A* structA = GetPointer();
} catch(bad_alloc ba) {
// ... handling the exception
}
return 0;
}
Alf, Ziko Thanks for the replies.
I did implement something that helps me achieve this. I am copying an
example.
struct strSP
{
int x;
float y;
strSP(int a,float b)
{
x=-9999;
y=-9999.9999;
}
strSP()
{
x=0;
y=0.0;
}
};
void* GetPointer()
{
void * pTempPtr;// = NULL;
if(NULL != ptrDynMem)
{
pTempPtr = ptrDynMem;
}
else
{
static strSP strSPInstance(0,0);
pTempPtr = &strSPInstance;
}
return pTempPtr;
}
Can you comment on this piece of code. I mean what are the obvious
loopholes that you see here?
With this there will be an instance of the struct always in the static
memory.
In the actual code, the default values of -9999 etc will be indicative
enough of usability of the pointer. I would not check for anything but
the values will be such that it will make the pointer returned
"unusable" or useless.
~Suraj