C++11 - 将非静态数据成员声明为 'auto'

标签 c++ c++11 auto variable-declaration

如果在声明中初始化非静态数据成员,C++11 是否允许将它们声明为“auto”?例如:

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.

因此,基本上根据 header 包含的顺序,data 的类型可能会非常不同。当然,auto x = 5; 不需要依赖于两阶段名称查找或 ADL,但是,我假设他们将其设为“一揽子”规则,否则,他们会必须为每个用例制定单独的规则,这会使事情变得非常复杂。

在同一篇论文中,作者提议取消此限制,但是,该提议似乎已被拒绝,可能是由于上述理由,而且无论初始化程序是什么,预期行为都可以相同。

关于C++11 - 将非静态数据成员声明为 'auto',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15236533/

相关文章:

c++ - 从聚合线程更新 QListView 使 GUI 卡住

c++ - Qt4 QTableWidget 使 Column resize to contents, interactive and aligned to table border

返回锁时的C++ 11 move

c++ - 将 C uint8_t 指针 + 大小组合转换为 C++ 迭代器

c++ - auto&& 告诉我们什么?

c++ - 从gdb中模板类的成员函数打印静态变量

c++ - 在 std::list 中,std::distance(it.begin(), std::prev(it.end())) 是否等于 list.size()?

c++ - 当向 std::enable_if 传递错误类型(double)而不是 std::complex 时,std::enable_if 无法执行操作

c++ - C++11 auto 关键字是否针对所有情况进行了准确定义?或者 : how does auto know what I intend?

c++ - 模板回调的包装器?