class 中的前向声明(不是嵌套的 class)

Forward declaration within a class (not a nested class)

我遇到了这个奇怪的前向声明(或其他东西),而不是正常的:

class A;
class B{
    A* var;
}

你可以做到

class B{
   class A* var;
}

现在这可能是一个详细的类型说明符,但我不确定。 我自己尝试过,没有任何问题,甚至让我的代码更简洁,但我担心它可能会导致我目前不知道的范围问题。

有人对此有见解吗?这是有效的向前减速吗?

示例:https://youtu.be/EIptJ0YrYg0?t=412

注意文档说:

Note that a new class name may also be introduced by an elaborated type specifier which appears as part of another declaration, but only if name lookup can't find a previously declared class with the same name.

因此,如果 class B 包含在命名空间中并且没有执行先前的 A 前向声明,那么它引用 n2::A 必须被定义。

Now this might be an elaborated type specifier, but I'm not sure about that.

是的。事实上,class A; 是一个使用精心设计的 class 说明符的声明。

but I'm afraid it may cause scoping issues that I'm currently unaware of

您唯一应该注意的与作用域相关的一点是,如果详细的类型说明符(它本身不是声明)是第一次引用 class,则行为与您向最近的名称空间或块作用域引入了前向声明。例如

namespace N {
  class foo {
     class bar {
       void func(class baz*);
     };
  };
};

...与

相同
namespace N {
  class baz;
  class foo {
     class bar {
       void func(baz*);
     };
  };
};

是的,这是一个有效的前向声明。它被称为精心设计的类型说明符。

引用来自 cppreference 的 elaborated type specifier

If the name lookup does not find a previously declared type name, the elaborated-type-specifier is introduced by class, struct, or union (i.e. not by enum), and class-name is an unqualified identifier, then the elaborated-type-specifier is a class declaration of the class-name.

它也可以用来引用已经声明的 class,即使它的名字被 non-type 声明隐藏了。