fork download
  1. #include <iostream>
  2.  
  3. // A class with a pointer and a getter that returns a reference.
  4. class A {
  5. std::string *text;
  6. public:
  7. std::string& GetText_old_way() { return *text; }
  8. auto GetText_pure_auto() { return *text; }
  9. auto GetText_pointer_arithmetic() -> decltype(*text) & { return *text; }
  10. public:
  11. A(std::string *text): text(text) {}
  12. };
  13.  
  14. // A class with a reference and a getter that returns a pointer.
  15. class B {
  16. std::string& text;
  17. public:
  18. std::string *GetText_old_way() { return &text; }
  19. auto GetText_pure_auto() { return &text; }
  20. auto GetText_pointer_arithmetic() -> decltype(&text) { return &text; }
  21. auto GetText_remove_reference() -> std::remove_reference_t<decltype(text)> * { return &text; }
  22. public:
  23. B(std::string& text): text(text) {}
  24. };
  25.  
  26. int main() {
  27. std::string text = "hello, world";
  28.  
  29. {//TEST
  30. A a(&text);
  31. unsigned int i{0};
  32.  
  33. std::cout << "-- Test 1:"<< std::endl;
  34. ++i; std::cout << i << ". " << a.GetText_old_way() << std::endl;
  35. ++i; std::cout << i << ". " << a.GetText_pointer_arithmetic() << std::endl;
  36. ++i; std::cout << i << ". " << a.GetText_pure_auto() << std::endl;
  37. std::cout << std::endl;
  38. }
  39.  
  40. {//TEST
  41. B b(text);
  42. unsigned int i{0};
  43.  
  44. std::cout << "-- Test 2:"<< std::endl;
  45. ++i; std::cout << i << ". " << *b.GetText_old_way() << std::endl;
  46. ++i; std::cout << i << ". " << *b.GetText_pointer_arithmetic() << std::endl;
  47. ++i; std::cout << i << ". " << *b.GetText_remove_reference() << std::endl;
  48. ++i; std::cout << i << ". " << *b.GetText_pure_auto() << std::endl;
  49. std::cout << std::endl;
  50. }
  51.  
  52. return 0;
  53. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
-- Test 1:
1. hello, world
2. hello, world
3. hello, world

-- Test 2:
1. hello, world
2. hello, world
3. hello, world
4. hello, world