Matthieu M.在这个答案中提出了一种访问保护模式,我以前见过,但从未有意识地考虑过这种模式:
class SomeKey {
friend class Foo;
SomeKey() {}
// possibly make it non-copyable too
};
class Bar {
public:
void protectedMethod(SomeKey);
};
只有 key 类的 friend
才能访问 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
}
};
它比将Foo
作为Bar
的friend
或使用更复杂的代理模式更能实现细粒度的访问控制。
请问是否已经有一个名称来描述这种方法,即是否是已知的模式?
Foo
能够委托其他类访问该键(当然,根据情况,委托可能是有用的),否则使键不可复制可能是有用的。 - James McNellis