C++ Logo

std-proposals

Advanced search

Idea: "friend" scope

From: Matthew Woehlke <mwoehlke.floss_at_[hidden]>
Date: Thu, 20 Jun 2019 17:41:33 -0400
I am struggling with the following code (grotesquely simplified):

  class a
  {
  public:
    static std::shared_ptr<a> create(int x)
    { return std::make_shared<a>(x); }

  protected:
    friend class std::shared_ptr<a>;

    a(int) {}
  };

...and I'm hardly alone: https://stackoverflow.com/questions/8147027.

Most of the existing approached are either ugly (requiring introduction
of "public" API that is made unusable outside of the class by using a
private type in the parameter list), or essentially relies on various
methods to circumvent access protection and can only access protected
constructors.

It occurred to me, there really ought to be a better way to fix this.
(Also, smart pointer return type polymorphism, but that's a different
discussion.) Poking around in libstdc++'s implementation of shared_ptr
inspired me to try friending `std::shared_ptr<a>`, but that doesn't work
either, since it is ultimately a helper function that constructs `a`. I
then wondered if it would be completely unreasonable to specify an
implementation detail that would permit this, although that's really
still the wrong thing to do.

Then I had a better, though perhaps crazy idea... what about introducing
a "friend scope"?

  static std::shared_ptr<a> create(int x)
  {
    friend
    {
      // Within this block, all access protection to `a` is suspended.
      ...
    }
  }

  // Bonus idea: as a method scope
  static std::shared_ptr<a> create(int x) friend
  { ... }


Is this plausible or completely insane? Would this be utterly impossible
to implement? Would the effects be too far-reaching (and if so, is there
a way to counter that while still achieving the goal)?

In short... does this look like an interesting idea that is worth pursuing?

-- 
Matthew

Received on 2019-06-20 16:43:24