c++ - Scott Meyers 第二版关于在 Effective C++ 中实现 nullptr 的一些问题?

标签 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*() constoperator T C::*() const 已在类中定义,因此可以自动内联。那么,为什么要再次添加 inline 呢?
  2. 为什么是void operator&() const;,而不是void operator&() = delete
  3. nullptr = {}; 是什么意思?

最佳答案

  1. 添加额外的内联是样式问题。该说明符与链接和 ODR 违规有关,而不是实际内联。所有内联成员函数定义和模板成员函数通常都隐式具有该说明符。我认为 Scott Meyers 出于教学原因将其添加到此处。

  2. Effective C++ 最初是为 C++03 编写的。那时还没有= delete。那时你只能声明但不定义函数。

  3. 这是聚合初始化。 nullptr_t 的这个实现即使在 C++03 中也可以像这样初始化。它创建 nullptr 的值。由于 nullptr_t 没有用户提供的默认 c'tor,因此它是必需的。

关于c++ - Scott Meyers 第二版关于在 Effective C++ 中实现 nullptr 的一些问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46129024/

相关文章:

c++ - 提取 try-catch 时出现运行时错误

c++ - Constexpr 函数作为 SFINAE 的模板参数

c++ - 如何在 C++ 中创建只有一个实例的类

C++0x 与 using 声明的混淆

c++ - 尝试构建 muParser:错误:'std::basic_ostream 的显式实例化但没有可用的定义

c++ - 您的计算机中缺少 api-ms-win-core-winrt-string-l1-1-0.dll

c++ - 使用不同比例因子缩放单个图像

C++ push_back vs Insert vs emplace

C++ endl 常量

c++ - 是否可以将对象实例移动到 QT 项目中不同代码点的不同线程?