对象与基本类型(四)

38 阅读1分钟

常量类型与常量表达式

  • 使用 const 声明常量对象

  • 是编译期概念,编译器利用其

    • 防止非法操作
    • 优化程序逻辑
  • 常量指针与顶层常量 (top-level const)

    • const int* p;
    • int* const p;
    • const int* const p;

常量指针可指向变量

常量引用 (也可绑定变量)

  • const int&
  • 可读但不可写
  • 主要用于函数形参
  • 可以绑定字面值

常量表达式 (从 c++11 开始)

  • 使用 constexpr 声明
  • 声明的是编译期常量
  • 编译器可以利用其进行优化
  • 常量表达式指针:constexpr 位于 * 左侧,但表示指针是常量表达式
#include <type_traits>

int main()
{
    constexpr const int* ptr = nullptr;
    std::cout << std::is_same_v<decltype(ptr), const int* const> << std::endl;
}