Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hello.

Is there a way
to get a compiler error message
by passing of NULL (explicitly) to a pointer parameter, please ? :)

void f(CWnd* pcTest)
{
}

void test()
{
  // would like to get an "error" here
  f(NULL);
}

The cases of f(const CWnd&) and f(CWnd*&)
are already checked.

Thank you ! :)
Posted

The best way is to change the function prototype such that it accepts a reference to a CWnd object:
void f(CWnd &obj)
{
 //blah
}

void test()
{
 //f(NULL); //compiler error!
 CWnd wnd;
 f(wnd); //will succeed.
}

If you're writing a multithreaded program, you might want to take thread safety into account.
 
Share this answer
 
I don't think that is possible, since NULL is a valid pointer, as far as the compiler is concerned. It just means that the pointer currently does not point to any object, which may be what the programmer wants. You could redefine NULL to some illegal value, but that would probably break your code elsewhere.
 
Share this answer
 
One trick is to provide a separate overload:

void f(char c);


which makes calls with a literal 0 ambiguous. The overload doesn't need an implementation. You'd have to specify f((CWnd*)0) to pick the correct overload if needed.

However, I would not recommend to use that. It's of questionable value, since it wouldn't even catch:

CWnd * wnd = 0;
f(wnd);


(which can't be caught - at least not easily - at compile time).

A simple ASSERT within f() should do the trick - or pass a reference, as suggested.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900