worldsite / blog.sc

Blogging soul chat, stay cool. via: https://blog.sc
3 stars 0 forks source link

const引用和const指针 #32

Open suhao opened 3 years ago

suhao commented 3 years ago

工作中,我们在某些情况下需要区分(const int p;) (int const p;) (int *const p;)三者,那么他们的区别是什么呢?

首先,我们来看下边的两个模板定义:

template <typename R, typename Receive, typename... Args>
bool Invoke(R (Receive::*method)(Args...), Args... args) {
  using Functor = FunctorAdapter<R, Receive, Args...>;
  return Invoke<Functor>(method, args...);
}

template <typename R, typename Receive, typename... Args>
bool Invoke(R (Receive::*method)(const Args...), Args &&... args) {
  using Functor = FunctorAdapter<R, Receive, const Args...>;
  return Invoke<Functor>(method, args...);
}

当method的参数为指针时,需要如何定义才能匹配上述两个模板调用呢? 这时候我们就需要使用 const type* const ,如下:

virtual void Method(const std::int32_t *const &) {}

一、const指针

int* p定义了一个普通的指针,const指针有如下几种情况:

  1. const int * p: 指向常量的指针
*p = 2;            // 错误,实际内存值无法通过p被修改,所以*p不能作为左值,
p = nullptr;     // 正确,p可以被修改
  1. int* const p:指向变量的常量指针,指针为常量
*p = nullptr;  // 正确,*p指向的内存可以通过p修改
p = nullptr;   // 错误,p是const的,无法修改,不能作为左值
  1. const int * const p:指向常量的常量指针,
*p = nullptr;  // 错误
p = nullptr;   // 错误

const在类型之后:修饰的是const前的类型,即变量的实际值不可变 const在指针之后:修改的是const前的指针,则指针不可变 const在类型之前:等同于在类型之后 不可变,则不能作为左值

二、const引用

  1. const int& b:引用常量
int i = 0;
const int& r1 = i;         // 正确
const int& r2 = 3;        // 正确
const int& r3 = i * 5;   // 正确
int& r4 = r1 * 2;          // 错误
int& r5 = 3;                // 错误
  1. int &const b:非法的,指针是对象而引用不是,不存在常量引用

术语中我们讲的常量引用,其实指的是引用常量

三、static

static const 和 const static是一样的

参考资料: