技术控

    今日:130| 主题:49332
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Passkey Idiom: More Useful Empty Classes

[复制链接]
耗盡我的温柔 发表于 2016-10-20 02:03:44
86 1

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
After last week’s post abouttag dispatchlet’s have a look at another example for useful empty classes: The passkey idiom can help us regain control that we would give up by simply making classes friend s.  
   The problem with friendship

  Friendship is the strongest coupling we can express in C++, even stronger than inheritance. So we’d better be careful and avoid it if possible. But sometimes we just don’t get around giving a class more access than another.
  A common example is a class that has to be created by a factory. That factory needs access to the class’ constructors. Other classes should not have that access to not circumvent the bookkeeping or whatever else makes the factory necessary.
   A problem of the friend keyword is that it gives access to everything. There is no way to tell the compiler that the factory should not have access to any other private elements except the constructor. It’s all or nothing.
  [code]class Secret {
friend class SecretFactory;
private:

  //Factory needs access:
  explicit Secret(std::string str) : data(std::move(str)) {}

  //Factory should not have access but has:
  void addData(std::string const& moreData);

private:
  //Factory DEFINITELY should not have access but has:
  std::string data;
};[/code]   Whenever we make a class a friend , we give it unrestricted access. We even relinquish the control of our class’ invariants, because the friend can now mess with our internals as it pleases.
   The passkey idiom

  Except there is a way to restrict that access. As so often, another indirection can solve the problem. Instead of directly giving the factory access to everything, we can give it access to a specified set of methods, provided it can create a little key token.
   
Passkey Idiom: More Useful Empty Classes-1 (everything,friendship,necessary,sometimes,coupling)

  [code]class Secret {
  class ConstructorKey {
    friend class SecretFactory;
  private:
    ConstructorKey() = default;
    ConstructorKey(ConstructorKey const&) = default;
  };
public:

  //Whoever can provide a key has access:
  explicit Secret(std::string str, ConstructorKey) : data(std::move(str)) {}

private:
  //these stay private, since Secret itself has no friends any more
  void addData(std::string const& moreData);

  std::string data;
};

class SecretFactory {
public:
  Secret getSecret(std::string str) {
    return Secret{std::move(str), {}}; //OK, SecretFactory can access
  }

  // void modify(Secret& secret, std::string const& additionalData) {
  //   secret.addData(additionalData); //ERROR: void Secret::addData(const string&) is private
  // }
};

int main() {
  Secret s{"foo?", {}}; //ERROR: Secret::ConstructorKey::ConstructorKey() is private

  SecretFactory sf;
  Secret s = sf.getSecret("moo!"); //OK
}[/code]   A few notes

   There are variants to this idiom: The key class need not be a private member of Secret here. It can well be a public member or a free class on its own. That way the same key class could be used as key for multiple classes.
   A thing to keep in mind is to make both constructors of the key class private, even if the key class is a private member of Secret . The default constructor needs to be private because sadly even though the key class itself is not accessible, it can be created via uniform initialization if it has no data members.
  [code]Secret s("foo?", {}); //Secret::ConstructorKey is not mentioned, so we don't access a private name or what?[/code]   There was a small discussion about that in the “cpplang” Slack channel a while ago, and it seems to be a loophole in the standard causing this unexpected behavior.
   The copy constructor needs to be private especially if the class is not a private member of Secret . Otherwise, this little hack could give us access too easily:
  [code]ConstructorKey* pk = nullptr;
Secret s("bar!", *pk);[/code]   While dereferencing an uninitialized or null pointer is undefined behavior, it will work in all major compilers, maybe triggering a few warnings. Making the copy constructor private closes that hole, so it is syntactically impossible to create a ConstructorKey object.
   Conclusion

  While it probably is not needed too often, small tricks like this one can help us to make our programs more robust against mistakes.
友荐云推荐




上一篇:Malware posing as Dual Instance app steals users’ Twitter credentials
下一篇:构建一套成功大数据基础设施需要遵循的七项要诀
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

小贝0 发表于 2016-10-24 10:09:27
刚起床,睁开眼就看到楼主的帖子了,顶一下!
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表