相关疑难解决方法(0)

这种面向密钥的访问保护模式是一种已知的习惯用法吗?

Matthieu M.在我之前看过的这个答案中提出了一种访问保护模式,但从未有意识地考虑过一种模式:

class SomeKey { 
    friend class Foo;
    SomeKey() {} 
    // possibly make it non-copyable too
};

class Bar {
public:
    void protectedMethod(SomeKey);
};
Run Code Online (Sandbox Code Playgroud)

这里只有一个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
    }
};
Run Code Online (Sandbox Code Playgroud)

它允许更多的细粒度访问控制不是制造Foo一个friendBar,避免了更复杂的代理模式.

有谁知道这种方法是否已经有一个名称,即,是一个已知的模式?

c++ design-patterns access-control friend

47
推荐指数
2
解决办法
8985
查看次数

标签 统计

access-control ×1

c++ ×1

design-patterns ×1

friend ×1