为什么在本地类中不允许静态数据成员? [英] Why aren't static data members allowed in local classes?

查看:858
本文介绍了为什么在本地类中不允许静态数据成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 static const 成员不能存在于本地类中的原因是什么?这似乎是一个相当愚蠢的限制。

What is the reasoning to why static const members cannot exist in local classes? It seems like a rather silly restriction.

示例:

void foo() {
  struct bar {
    int baz() { return 0; }   // allowed
    static const int qux = 0; // not allowed?!?
  };
}

struct non_local_bar {
  int baz() { return 0; }   // allowed
  static const int qux = 0; // allowed
};

标准报价(9.8.4):

Quote from standard (9.8.4):


本地类不得有静态数据成员。

A local class shall not have static data members.


推荐答案

从标准章节9.4.2:

From the standard section 9.4.2:


如果静态数据成员是const整数或const枚举
类型,它在类定义中的声明可以指定一个
常量初始化器,它应该是一个整数常量表达式。
在这种情况下,成员可以在其范围内出现在整数常量表达式
中。 如果在程序中使用,并且命名空间范围定义
不包含初始化程序,则该成员仍然在命名空间
scope
中定义

基本上,本地类没有链接,静态数据成员需要链接。

Basically, local classes have no linkage, and static data members require a linkage.

在命名空间范围中定义一个本地类的静态数据成员的方法(初始化器的声明不是定义),不允许它们,不管它们是否是const整数类型。在表面上看起来好像编译器应该能够内联值,但是如果您尝试访问指向成员的指针,会发生什么?使用命名空间范围的类你只会得到一个链接器错误,但是本地类没有链接。

Since there's no way to define a static data member of a local class in namespace scope (a declaration with an initializer is not a definition), they are not allowed, whether they are of const integral type or not. On the surface it may seem like the compiler should just be able to inline the value, but then what happens if you try to access a pointer to the member? With namespace scoped classes you'd just get a linker error, but local classes have no linkage.

我想在理论上他们可以允许你使用静态const整数类型在局部类中,只要它们只用于整数常量表达式,但是它可能只会给标准体和编译器供应商带来太大的负担,以区分非常小的实际价值;本地静态变量可以从本地类访问,所以使用本地静态const应该是一样好。

I guess in theory they could just allow you to use static const integral types in local classes as long as they are only used in integral constant expressions, but it would probably just put too much of a burden on the standards body and compiler vendors to differentiate for very little practical value; local static variables are accessible from local classes, so using a local static const should be just as good.

这篇关于为什么在本地类中不允许静态数据成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆