3

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 <memory>

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

#include "a.hpp"

int main()
{}

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

Questions:

  1. What's the syntax for <class A_impl>? 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.

aafulei
  • 2,085
  • 12
  • 27

1 Answers1

6

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 identifier 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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Daniel Jour
  • 15,896
  • 2
  • 36
  • 63
  • Thanks for the prompt reply! Do you agree with the comment to the question that `elaborated type specifier` applies to this case? – aafulei Jan 06 '20 at 09:02
  • "Elaborated type specifier" definitively applies ... that's basically the term of that syntax construct ... which is also used in a "normal" forward declaration. I'm not sure about the differences... – Daniel Jour Jan 06 '20 at 09:30
  • Up voted! Didn't realize this also works, always used the `class T; std::unique_ptr p; myself.` – Tanveer Badar Mar 08 '20 at 11:10