Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some questions about implementation of nullptr in Effective C++ by Scott Meyers, Second Edition?

Tags:

c++

const // It is a const object...
class nullptr_t 
{
  public:
    template<class T>
    inline operator T*() const // convertible to any type of null non-member pointer...
    { return 0; }

    template<class C, class T>
    inline operator T C::*() const   // or any type of null member pointer...
    { return 0; }

  private:
    void operator&() const;  // Can't take address of nullptr

} nullptr = {};
  1. operator T*() const and operator T C::*() const are already defined in class, so it can inline automatically. So, why add inline again?
  2. why void operator&() const;, notvoid operator&() = delete?
  3. what does nullptr = {}; mean?
like image 631
Chen Li Avatar asked Sep 09 '17 09:09

Chen Li


People also ask

Can I use nullptr instead of null?

Nullptr vs NULL NULL is 0 (zero) i.e. integer constant zero with C-style typecast to void* , while nullptr is prvalue of type nullptr_t , which is an integer literal that evaluates to zero. For those of you who believe that NULL is the same i.e. (void*)0 in C and C++.

Does nullptr evaluate to false?

Also, remembering that nullptr evaluates to false is another bit of information you need to store in the back of your brain to properly decode the code you're reading.

Why do we use nullptr?

The nullptr keyword can be used to test if a pointer or handle reference is null before the reference is used. Function calls among languages that use null pointer values for error checking should be interpreted correctly. You cannot initialize a handle to zero; only nullptr can be used.

Is More Effective C++ still relevant?

The Effective C++ is still very relevant, and is not superseded by the new book.


1 Answers

  1. Adding the extra inline is a matter of style. That specifier has to do with linkage and ODR violations, not actual inlining. All inline member function definitions and template member functions in general have that specifier implicitly. I assume Scott Meyers added it there for pedagogical reasons.

  2. Effective C++ was written for C++03 originally. There was no = delete back then. Declaring but not defining a function was all you could do back then.

  3. This is aggregate initialization. This implementation of nullptr_t can be initialized like that even in C++03. It creates the value of nullptr. Since nullptr_t doesn't have a user provided default c'tor, it's required.

like image 52
StoryTeller - Unslander Monica Avatar answered Oct 06 '22 00:10

StoryTeller - Unslander Monica