10

[class.dtor]/1 contains the following sentence:

Each decl-specifier of the decl-specifier-seq of a destructor declaration (if any) shall be friend, inline, or virtual.

I'm really interested in seeing an example of the use of a destructor with a friend specifier.

Alexander
  • 2,581
  • 11
  • 17

2 Answers2

11

Suppose you want to allow private members of class A to be used in class B. No problem, you declare B as a friend inside A.

Suppose further that you want to restrict the usage to B's destructor only. Thus, you only declare B's destructor as a friend:

struct A
{
private:
    // some private stuff
    friend B::~B();
};

See this example on ideone.

lisyarus
  • 15,025
  • 3
  • 43
  • 68
  • 1
    Apparently you can declare an implicitly declared function a friend, too: [Like this.](http://coliru.stacked-crooked.com/a/ecd5350d985b3a5f) – jrok Apr 04 '18 at 12:11
  • But you don't need this. See the counterexample [here](http://coliru.stacked-crooked.com/a/ffd40896fbe8cb0e). – Alexander Apr 04 '18 at 12:28
  • @Alexander True, but you don't even *need* to make anything private - all this are just different design decisions. – lisyarus Apr 04 '18 at 12:41
  • Your "counterexample" `B::~B()` doesn't use anything private from `A`. – molbdnilo Apr 04 '18 at 12:45
  • @molbdnilo I don't need to use any private member of `A` to do what the OP's code does. That's why I called it a counterexample. – Alexander Apr 04 '18 at 12:49
4

Basically, if you declare a destructor of say class A inside the class definition of class B as friend, A::~A may be able to access private elements of B. The same applies for any member function of A. This can be useful if you want to only allow specific functions of A to be able to access B's private members instead of declaring it a full friend class.

class B;

struct A {
   A() : b{ new B } { }
   B* b;
   ~A();
};

class B {
   friend A::~A();
   void member() { } 
};

A::~A() {
   b->member(); // possible as ~A is friend
   delete b;
}
Jodocus
  • 7,493
  • 1
  • 29
  • 45
  • @Leon Because a trivial main function is missing that would add nothing relevant to the example. The intention of this answer was to give an usecase, not to deliver a program with unnecessary details. – Jodocus Apr 11 '18 at 18:06