c++ - 函数定义中的四重 "const"

标签 c++ constants language-lawyer

我想知道 C++ 如何使用其 const 关键字。

我有以下函数定义。这看起来很疯狂,但工作得很好。

const int const * const Get(){ return new int(1); } const

我知道 const 的每个位置的含义,这个问题不是关于 const 关键字的位置的含义。

我对 const 关键字的使用感到很困惑,因为你可以复制它们。

const int const const * const Get(){ return new int(1); } const

// or even

const const int const const * const const Get(){ return new int(1); } const const

// or even yet

const const const int const const const * const const const Get(){ return new int(1); } const const const

为什么语言允许你这样做?

编辑: 此代码可以在 Visual Studio 2013、Visual C++ 编译器中编译。我不确定编译器的实际名称。

编辑2: 所以答案是这不符合标准。代码仅在不使用 /Za 选项的情况下编译。

我投票结束这个问题。

最佳答案

标准中不允许在同一类型说明符序列中显式重复 const

[dcl.type]/2(强调我的)

As a general rule, at most one type-specifier is allowed in the complete decl-specifier-seq of a declaration or in a type-specifier-seq or trailing-type-specifier-seq.

...

const can be combined with any type specifier except itself.

从以下引述(由@davidhigh 找到)中可能会认为这是允许的:

[dcl.type.cv]/1

There are two cv-qualifiers, const and volatile. Each cv-qualifier shall appear at most once in a cv-qualifier-seq. If a cv-qualifier appears in a decl-specifier-seq, the init-declarator-list of the declaration shall not be empty. [ Note: 3.9.3 and 8.3.5 describe how cv-qualifiers affect object and function types. — end note ] Redundant cv-qualifications are ignored. [ Note: For example, these could be introduced by typedefs. — end note ]

但是,此规则允许通过模板或 typedef 中的替换出现的 const 重复,而不是那些由程序员显式输入的内容。

以你的一个例子为例:

const const int const const * const const Get(){ return new int(1); } const const

前四个 const 都应用于 int,违反了上面发布的规则。

接下来的两个 const 适用于指针并且根据相同的规则无效。

最后两个 const 甚至不是 Get 声明的一部分。它们将应用于解析器接下来找到的任何内容,根据与上述相同的规则或其他 C++ 语法规则变得无效。

VS2013 可能会使用语言扩展来编译此类代码,但这不是标准行为。 gcc 5.1.0clang 3.5.1都将拒绝编译您的代码并提供合理的诊断。

关于c++ - 函数定义中的四重 "const",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30798661/

相关文章:

通过引用传递的 C++0x 初始化列表

Objective-C 重新定义类

c# - 为什么 IsLiteral 对十进制返回 false?

c++ - ref-qualifier `const &&` 有什么用?

c++ - 为什么对引用的 const 引用会失去其常量性?

c++ - Pedantic : What Is A Source File? 什么是 header ?

c++ - TRY/CATCH_ALL 与 try/catch

c++ - 静态链接可以导致执行一些初始化例程吗?

c++ - 将原始指针的所有权转移到 unique_ptr

c++ - Const static 对 const static 映射的引用集