Perfectly emulate nullptr

2019-06-21 03:29发布

问题:

I got tired of waiting for compiler support of nullptr (gcc 4.6 does but it's so new few distributions support it).

So as a stop gap until nullptr is fully supported I decided to emulate it. There are two examples of emulation: one from here, and one from wikibooks.

Of note, neither implementation mentions an operator ==. However, without one, the following code will not compile.

int* ptr = nullptr;
assert( ptr == nullptr ); // error here: missing operator ==

Is this operator == error a compiler bug?
Is operator == (and !=, <, <=, etc) needed to more perfectly emulate nullptr?
What else is different between an emulated nullptr and the real deal?

回答1:

You compiled it with C++0x compiler that failed for unknown reason. It compiles fine in C++03.



回答2:

Yes, you should implement such a thing. I am, however, surprised that the implicit conversion operators aren't kicking in and allowing you to compare without providing an explicit operator.

template<typename T> bool operator==(T* ptr, nullptr_t null) {
    return ptr == 0;
}
template<typename C, typename R> bool operator==(R C::* ptr, nullptr_t null) {
    return ptr == 0;
}
// And the reverse


回答3:

It's actually mentioned in the official proposal from your first example reference:

Experiments with several popular existing compilers show that it generates poor and/or misleading compiler diagnostics for several of the common use cases described in section 2. (Examples include: “no conversion from „const ‟ to „int‟”; “no suitable conversion function from „const class ‟ to „int‟ exists”; “a template argument may not reference an unnamed type”; “no operator „==‟ matches these operands, operand types are: int == const class ”.) We believe that compilers will still need to add special knowledge of nullptr in order to provide quality diagnos- tics for common use cases.

So you should fill this gap yourself if the compiler doesn't yet.