使用 `class` 关键字后面跟着一个未声明的标识符

huangapple go评论98阅读模式
英文:

Using `class` keyword followed by an undeclared identifier

问题

以下是翻译好的部分:

// a.hpp

#include <memory>

class A
{
    std::unique_ptr<class A_impl> my;
};
// a.cpp

#include "a.hpp"

int main()
{}

问题:

  1. <class A_impl> 的语法是什么?在未声明的标识符前面加上 class 是什么意思?这被称为什么?它是否在 A_impl 上执行了“前向声明”?我还没有提到标识符 A_impl。编译器为什么会接受这个?

  2. 如果这可能与任何“设计模式”有关,请帮助我识别它。

请指出正确的方向。

英文:

The following hpp and cpp files are an excerpt from a large program that I am working with. It will compile with g++ -std=c++17 -pedantic -Wall -Wextra.

// a.hpp

#include &lt;memory&gt;

class A
{
    std::unique_ptr&lt;class A_impl&gt; my;
};
//a.cpp

#include &quot;a.hpp&quot;

int main()
{}

But I don't understand about the syntax on the line regarding the unique pointer.

Questions:

  1. What's the syntax for &lt;class A_impl&gt;? What's this (putting class before an undeclared identifier) called? Is it doing a "forward declaration" on A_impl or what? I haven't said anything about the identifier A_impl. How come the compiler is okay with that?

  2. If this happens to be possibly related to any "design pattern", please help me identify it.

Please point out the right direction.

答案1

得分: 6

  • "Is it doing a 'forward declaration' on A_impl or what?"

    • 它对 A_impl 进行了 "前向声明" 吗?
  • "Exactly. What's probably confusing about it is that it's using an elaborated type specifier in the template argument to do so. Differences to a 'normal' forward declaration."

    • 确切地说,可能让人感到困惑的是它在模板参数中使用了一个详细类型说明符来执行此操作。与 '普通' 前向声明的区别。
  • "I haven't said anything about the identifier type A_impl. How come the compiler is okay with that?"

    • 我还没有提到关于 标识符 类型 A_impl 的任何内容。编译器怎么会没问题呢?
  • "std::unique_ptr can be instantiated with an incomplete type - just like a raw pointer."

    • std::unique_ptr 可以用不完整的类型来实例化 - 就像原始指针一样。
  • "If this happens to be possibly related to any 'design pattern', how can I identify it?"

    • 如果这可能与任何 '设计模式' 有关,我该如何识别它?
英文:

> Is it doing a "forward declaration" on A_impl or what?

Exactly. What's probably confusing about it is that it's using an elaborated type specifier in the template argument to do so. Differences to a "normal" forward declaration

> I haven't said anything about the <s>identifier</s> type A_impl. How come the compiler is okay with that?

std::unique_ptr can be instantiated with an incomplete type - just like a raw pointer.

> If this happens to be possibly related to any "design pattern", how can I identify it?

The PIMPL - "pointer to implementation" idiom.

huangapple
  • 本文由 发表于 2020年1月6日 16:51:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/59609097.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定