fork download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. template <typename T>
  5. struct propagating_unique_ptr : std::unique_ptr<T> {
  6. using std::unique_ptr<T>::unique_ptr;
  7. using std::unique_ptr<T>::operator =;
  8.  
  9. const T *get() const noexcept {
  10. return std::unique_ptr<T>::get();
  11. }
  12. T *get() noexcept {
  13. return std::unique_ptr<T>::get();
  14. }
  15.  
  16. const T &operator *() const noexcept {
  17. return std::unique_ptr<T>::operator *();
  18. }
  19. T &operator *() noexcept {
  20. return std::unique_ptr<T>::operator *();
  21. }
  22.  
  23. const T *operator -> () const noexcept {
  24. return std::unique_ptr<T>::get();
  25. }
  26. T *operator -> () noexcept {
  27. return std::unique_ptr<T>::get();
  28. }
  29. };
  30.  
  31. struct foo {
  32. foo() : value_ptr_(std::make_unique<int>(3)) {}
  33. void increment() {
  34. ++(*value_ptr_); // OK
  35. }
  36. int get_value() const {
  37. return *value_ptr_;
  38. }
  39. propagating_unique_ptr<int> value_ptr_;
  40. };
  41.  
  42. int main() {
  43. const foo my_foo;
  44. std::cout << my_foo.get_value() << std::endl;
  45. my_foo.increment(); // compiler error
  46. std::cout << my_foo.get_value() << std::endl;
  47. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function ‘int main()’:
prog.cpp:45:22: error: passing ‘const foo’ as ‘this’ argument discards qualifiers [-fpermissive]
     my_foo.increment(); // compiler error
                      ^
prog.cpp:33:10: note:   in call to ‘void foo::increment()’
     void increment() {
          ^~~~~~~~~
stdout
Standard output is empty