简体   繁体   English

const和constexpr指针之间的区别

[英]Difference between const and constexpr pointer

What is the difference between the following two pointer definitions 以下两个指针定义之间有什么区别

int i = 0;
const int *p = &i;
constexpr int *cp = &i;

const int *p = &i; means: 手段:

  • p is non-const: it can be reassigned to point to a different int p是非const的:它可以被重新分配以指向不同的int
  • i cannot be modified through p without use of a cast i不能通过p修改而不使用演员表

constexpr int *cp = &i; means: 手段:

  • cp is const : it cannot be reassigned cpconst :它不能被重新分配
  • i can be modified through p i 可以通过p修改

In both cases, p is an address constant if and only if i has static storage duration. 在这两种情况下,当且仅当i具有静态存储持续时间时, p是地址常量。 However, adding constexpr will cause a compilation error if applied to something that is not an address constant. 但是,如果应用于不是地址常量的东西,添加constexpr将导致编译错误。

To put that another way: constexpr int *cp = &i; 换句话说: constexpr int *cp = &i; and int *const cp = &i; int *const cp = &i; are very similar; 非常相似; the only difference is that the first one will fail to compile if cp would not be an address constant. 唯一的区别是,如果cp不是地址常量,第一个将无法编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM