c++ - 指针中的 constexpr 有区别吗

标签 c++ pointers c++11 constant-expression

constexpr int *np = nullptrint const *np = nullptr 有什么区别?

在这两种情况下,

np 都是一个指向 null 的常量指针。 constexpr 在指针上下文中是否有任何特定用途。

最佳答案

如果您尝试对指针做任何事情并在常量表达式中使用结果,则必须将指针标记为 constexpr。简单的例子是指针运算,或指针取消引用:

static constexpr int arr[] = {1,2,3,4,5,6};
constexpr const int *first = arr;
constexpr const int *second = first + 1; // would fail if first wasn't constexpr
constexpr int i = *second;

在上面的例子中,second 只能是 constexpr 如果 first 是。类似地,如果 secondconstexpr

,则 *second 只能是常量表达式

如果您尝试通过指针调用constexpr 成员函数并将结果用作常量表达式,则您通过它调用的指针本身必须是常量表达式

struct S {
    constexpr int f() const { return 1; }  
};

int main() {
    static constexpr S s{};
    const S *sp = &s;
    constexpr int i = sp->f(); // error: sp not a constant expression
}

如果我们改为说

constexpr const S *sp = &s;

那么上面的作品就可以了。请注意,上面确实(错误地)使用 gcc-4.9 编译和运行,但不是 gcc-5.1

关于c++ - 指针中的 constexpr 有区别吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32064699/

相关文章:

c++ - 从目标文件列表 (*.o) 构建库 (lib.a) 的 makefile

c - 使用指针功能 - 1 台设备上的 2 个独立应用程序

c++ - nullptr 作为 boost::any 映射的标志值

c++ - 基于范围的 for 循环可以知道结尾吗?

c++ - 使用 const 引用删除引用

c++ - 尝试用用户输入填充数组

c++ - 如何使用 C++ 中的 MAPI 以编程方式将带附件的电子邮件发送给已知收件人? MAPISendMail()

c++ - 存储或反射(reflect)在变量的 "reference level"

c - 将文件指针分配给另一个时出现段错误

c - 函数不打印结果