fork(3) download
  1. #include <memory>
  2.  
  3. template<
  4. class T,
  5. class Deleter = std::default_delete<T>
  6. > class transitive_ptr : public std::unique_ptr<T,Deleter>
  7. {
  8. public:
  9. // inherit typedefs for the sake of completeness
  10. typedef
  11. typename std::unique_ptr<T,Deleter>::pointer
  12. pointer;
  13. typedef
  14. typename std::unique_ptr<T,Deleter>::element_type
  15. element_type;
  16. typedef
  17. typename std::unique_ptr<T,Deleter>::deleter_type
  18. deleter_type;
  19.  
  20. // extra typedef
  21. typedef
  22. const typename std::remove_pointer<pointer>::type*
  23. const_pointer;
  24.  
  25. // inherit constructor
  26. using std::unique_ptr<T,Deleter>::unique_ptr;
  27.  
  28. // add transitively const version of get()
  29. pointer get() {
  30. return std::unique_ptr<T,Deleter>::get();
  31. }
  32. const_pointer get() const {
  33. return std::unique_ptr<T,Deleter>::get();
  34. }
  35.  
  36. // add transitively const version of operator*()
  37. typename std::add_lvalue_reference<T>::type
  38. operator*() {
  39. return *get();
  40. }
  41. typename std::add_lvalue_reference<const T>::type
  42. operator*() const {
  43. return *get();
  44. }
  45.  
  46. // add transitively const version of operator->()
  47. pointer operator->() {
  48. return get();
  49. }
  50. const_pointer operator->() const {
  51. return get();
  52. }
  53. };
  54.  
  55. struct A {
  56. transitive_ptr<int> x;
  57. A(): x{new int} {}
  58. };
  59.  
  60. int main() {
  61. const A a;
  62. *a.x = 3;
  63. }
Compilation error #stdin compilation error #stdout 0s 3424KB
stdin
Standard input is empty
compilation info
prog.cpp: In function ‘int main()’:
prog.cpp:62:10: error: assignment of read-only location ‘a.A::x.transitive_ptr<T, Deleter>::operator*<int, std::default_delete<int> >()’
     *a.x = 3;
          ^
stdout

Standard output is empty