请选择 进入手机版 | 继续访问电脑版

技术控

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

[其他] Passkey Idiom: More Useful Empty Classes

[复制链接]
耗盡我的温柔 发表于 2016-10-20 02:03:44
237 1
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.
  1. class Secret {
  2. friend class SecretFactory;
  3. private:
  4.   //Factory needs access:
  5.   explicit Secret(std::string str) : data(std::move(str)) {}
  6.   //Factory should not have access but has:
  7.   void addData(std::string const& moreData);
  8. private:
  9.   //Factory DEFINITELY should not have access but has:
  10.   std::string data;
  11. };
复制代码
  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

Passkey Idiom: More Useful Empty Classes-1-技术控-everything,friendship,necessary,sometimes,coupling

  1. class Secret {
  2.   class ConstructorKey {
  3.     friend class SecretFactory;
  4.   private:
  5.     ConstructorKey() = default;
  6.     ConstructorKey(ConstructorKey const&) = default;
  7.   };
  8. public:
  9.   //Whoever can provide a key has access:
  10.   explicit Secret(std::string str, ConstructorKey) : data(std::move(str)) {}
  11. private:
  12.   //these stay private, since Secret itself has no friends any more
  13.   void addData(std::string const& moreData);
  14.   std::string data;
  15. };
  16. class SecretFactory {
  17. public:
  18.   Secret getSecret(std::string str) {
  19.     return Secret{std::move(str), {}}; //OK, SecretFactory can access
  20.   }
  21.   // void modify(Secret& secret, std::string const& additionalData) {
  22.   //   secret.addData(additionalData); //ERROR: void Secret::addData(const string&) is private
  23.   // }
  24. };
  25. int main() {
  26.   Secret s{"foo?", {}}; //ERROR: Secret::ConstructorKey::ConstructorKey() is private
  27.   SecretFactory sf;
  28.   Secret s = sf.getSecret("moo!"); //OK
  29. }
复制代码
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.
  1. Secret s("foo?", {}); //Secret::ConstructorKey is not mentioned, so we don't access a private name or what?
复制代码
  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:
  1. ConstructorKey* pk = nullptr;
  2. Secret s("bar!", *pk);
复制代码
  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.
小贝0 发表于 2016-10-24 10:09:27
刚起床,睁开眼就看到楼主的帖子了,顶一下!
回复 支持 反对

使用道具 举报

我要投稿

推荐阅读


回页顶回复上一篇下一篇回列表
手机版/c.CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 | 粤公网安备 44010402000842号 )

© 2001-2017 Comsenz Inc.

返回顶部 返回列表