Is this key-oriented access-protection pattern a known idiom?
Matthieu M. brought up a pattern for access-protection in this answer that i'd seen before, but never conciously considered a pattern:
class SomeKey {
friend class Foo;
SomeKey() {}
// possibly make it non-copyable too
};
class Bar {
public:
void protectedMethod(SomeKey);
};
Here only a friend
of the key class has access to protectedMethod()
:
class Foo {
void do_stuff(Bar& b) {
b.protectedMethod(SomeKey()); // fine, Foo is friend of SomeKey
}
};
class Baz {
void do_stuff(Bar& b) {
b.protectedMethod(SomeKey()); // error, SomeKey::SomeKey() is private
}
};
It allows more fine-granular access-control than making Foo
a friend
of Bar
and avoids more complicated proxying patterns.
Does anyone know whether this approach already has a name, i.e., is a known pattern?
Solution 1:
Thanks to your other question it looks like this pattern is now known as the "passkey" pattern.
In C++11, it gets even cleaner, because instead of calling
b.protectedMethod(SomeKey());
you can just call:
b.protectedMethod({});
Solution 2:
It seems that this idiom like one mentioned in another SO question here. It is called Attorney-Client idiom and described in more details there.