fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. /**
  5. * @brief Defines a passkey for type T.
  6. */
  7. template <typename T>
  8. class PassKey
  9. {
  10. private:
  11. // befriend T so that only T can create a PassKey object
  12. friend T;
  13.  
  14. // make default constructor private so that only T can access it
  15. PassKey() {}
  16.  
  17. // noncopyable, non-assignable so that key can not be re-used
  18. PassKey(const PassKey&) = delete;
  19. PassKey& operator=(const PassKey&) = delete;
  20. };
  21.  
  22. struct B;
  23.  
  24. struct A
  25. {
  26. void doSomething(PassKey<B>) const
  27. {}
  28. };
  29.  
  30. struct B
  31. {
  32. void callDoSomething(const A& a) const
  33. {
  34. a.doSomething({});
  35. }
  36. };
  37.  
  38.  
  39.  
  40. int main() {
  41. A a;
  42. B b;
  43. b.callDoSomething(a);
  44. int FraudKey=0;
  45. a.doSomething(reinterpret_cast<PassKey<B>&>(FraudKey));
  46. return 0;
  47. }
Compilation error #stdin compilation error #stdout 0s 4540KB
stdin
Standard input is empty
compilation info
prog.cpp: In function ‘int main()’:
prog.cpp:45:55: error: use of deleted function ‘PassKey<T>::PassKey(const PassKey<T>&) [with T = B]’
  a.doSomething(reinterpret_cast<PassKey<B>&>(FraudKey));
                                                       ^
prog.cpp:18:5: note: declared here
     PassKey(const PassKey&) = delete;
     ^~~~~~~
prog.cpp:26:7: note:   initializing argument 1 of ‘void A::doSomething(PassKey<B>) const’
  void doSomething(PassKey<B>) const
       ^~~~~~~~~~~
stdout
Standard output is empty