Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to assign nullptr to a function pointer variable?

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?

like image 306
Alex Avatar asked Apr 27 '12 12:04

Alex


People also ask

Should I initialize a pointer to nullptr?

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.

Can we assign a null value to a pointer variable?

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.

Should I use null or nullptr C++?

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 .

Are function pointers safe?

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.


1 Answers

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.

like image 137
bames53 Avatar answered Sep 21 '22 16:09

bames53