I created a function that accepts a function pointer, e.g.
typedef CString(*GetLabelFunc)(const CSomeObject* const pObject);
void DoSomething(GetLabelFunc funcGetLabel);
The function may receive a null pointer and will return an empty string in that case. This works perfectly fine in MSVC++ 2010 when using NULL and nullptr as parameter as well - but I do not consider a successful compilation a safe harbor in such special cases ...
Now I wondered if passing nullptr
is equivalent to NULL
for function pointers. The reason why I am asking is that for instance void*
does not accept function pointers (or it least it should not be used). So maybe there is a similar reason that nullptr should not be used for function pointers - meaning is it designed to work for object pointers only?
nullptr is a good value to initialize, to indicate that there is no memory pointed to by the pointer. Also, delete operation on nullptr is safe, whereas delete on arbitrary values (which is typically the case when you don't initialize the pointer) can cause Segmentation faults.
It is always a good practice to assign the pointer NULL to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer.
As I mentioned above, the general rule of thumb that I recommend is that you should start using nullptr whenever you would have used NULL in the past. As a reminder, since C++11, NULL can be either an integer literal with value zero, or a prvalue of type std::nullptr_t .
Pointers to member functions in C++ This is how C++ uses function pointers when dealing with member functions of classes or structs. These are invoked using an object pointer or a this call. They are type safe in that you can only call members of that class (or derivatives) using a pointer of that type.
Yes, nullptr is specified to be convertible to the null pointer value for all pointer types, including function pointer types.
See [conv.ptr] 4.10/1 and [basic.compound] 3.9.2/3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With