[cfe-dev] Clang Sources, friend classes can't access private members?

via cfe-dev cfe-dev at lists.llvm.org
Tue May 7 07:27:27 PDT 2019


Hi all!
I found that in clang sources, in Sema.h in particular,
it is required to add class predeclaration before friending it, like this:

  class DelayedDiagnostics; // predeclaration is required here, otherwise it won't compiled

  class DelayedDiagnosticsState {
    sema::DelayedDiagnosticPool *SavedPool;
    friend class Sema::DelayedDiagnostics;
  };
  // ...
  class DelayedDiagnostics {
  // ...
    DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
      DelayedDiagnosticsState state;
      state.SavedPool = CurPool; // Private access.
      // ...
    }
  };

And yet it contradicts standard, which states that the name of the class that is used in this friend declaration does not need to be previously declared.

Honestly I didn't try to debug it. I tried to reproduce it though, but failed. The example below compiled with no errors:

namespace clang {
class Sema {
  public:
  class A {
    int x;
    friend class B;
  };

  class B {
    A a;
    void f() {
      a.x = 1; // access private member of A, no error!
    }
  };
};
} // namespace clang

It looks like I'm missing something... Anybody knows why we should predeclare friend classes in clang::Sema?

Thanks!
Stepan Dyatkovskiy




More information about the cfe-dev mailing list