如果非静态数据成员在声明中被初始化,C++11 是否允许将非静态数据成员声明为“自动”?例如:
struct S
{
auto x = 5; // in place of 'int x = 5;', which is definitely allowed
};
GCC 4.7 拒绝上述代码,而接受 int x = 5;
.
假设这不是编译器错误,而是标准确实不允许,为什么不呢?它与声明局部变量 auto
一样有用。
最佳答案
禁止非静态成员的规则在 7.1.6.4 第 4 条:
The auto type-specifier can also be used in declaring a variable in the condition of a selection statement (6.4) or an iteration statement (6.5), in the type-specifier-seq in the new-type-id or type-id of a new-expression (5.3.4), in a for-range-declaration, and in declaring a static data member with a brace-or-equal-initializer that appears within the member-specification of a class definition (9.4.2).
我发现它是静态的原因here这反射(reflect)了 James McNellis 在评论中的解释。
One national body dislikes allowing the auto type-specifier for non-statics. From an e-mail to the authors:
template< class T > struct MyType : T { auto data = func(); static const size_t erm = sizeof(data); };
In order to determine the layout of X, we now have 2-phase name lookup and ADL. Note that func could be either a type or a function; it may be found in T, the namespace of MyType, the associated namespace(s) of T when instantiated, the global namespace, an anonymous namespace, or any namespaces subject to a using directive. With care we could probably throw some concept_map lookup in for luck. Depending on the order of header inclusion I might even get different results for ADL, and break the One Definition Rule - which is not required to be diagnosed.
Because of this controversy, the authors no longer propose that auto be allowed for non-static data members.
所以,基本上根据头包含的顺序,data
的类型可能会有很大的不同。当然,auto x = 5;
不需要依赖 2 阶段名称查找或 ADL,但是,我假设他们将其设为“一揽子”规则,否则,他们会必须为每个用例制定单独的规则,这会使事情变得非常复杂。
在同一篇论文中,作者提议取消这个限制,然而,这个提议似乎被拒绝了,可能是由于上述理由,而且无论初始化器是什么,预期的行为都可以相同。
关于C++11 - 将非静态数据成员声明为 'auto',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11302981/