【发布时间】:2011-03-14 07:07:34
【问题描述】:
Matthieu M. 在this answer 中提出了一种访问保护模式,我以前见过,但从未有意识地考虑过这种模式:
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 设置为friend 或Bar 相比,它允许更细粒度的访问控制,并避免更复杂的代理模式。
有谁知道这种方法是否已经有了名字,即,是一种已知的模式吗?
【问题讨论】:
-
可能是一个展示您将如何实际使用这些类的想法。
-
@Neil:对,这可能并不明显。
-
使密钥不可复制可能很有用,除非您希望
Foo能够委派对其他类的访问(当然,委派可能很有用,具体取决于具体情况)。跨度> -
问:可以用下面的 hack 打败它吗? char* some_junk_object=new char[...]; SomeKey* p=(SomeKey*)(some_junk_object); b.protectedMethod(*p);如果你所做的只是依赖类型系统,那么颠覆是微不足道的。 (我见过类似的密钥系统以类似的方式严重失败。)
-
@Owen:如果 copy-ctor 是可访问的,是的 - 但同样没有办法保护 C++ 中的所有内容,总有一些 hack 围绕它。我们希望防止错误,而不是故意滥用。如果我们不希望委托并将 copy-ctor 设为非公开,那么您的 hack 将行不通。
标签: c++ design-patterns friend access-control