fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. class A {
  5. public:
  6. std::vector<int>& get()
  7. {
  8. std::cout << "A::get()" << std::endl;
  9. return myVector;
  10. }
  11. const std::vector<int>& get() const
  12. {
  13. std::cout << "A::get() const" << std::endl;
  14. return myVector;
  15. }
  16.  
  17. private:
  18. std::vector<int> myVector;
  19. };
  20.  
  21. int main()
  22. {
  23. A myA;
  24. myA.get().push_back(1);
  25. for (const auto& v: myA.get()) { } // it involve not const get method
  26. // force application to const instance
  27. std::cout << "use const reference to instance" << std::endl;
  28. { const A &myAC = myA;
  29. for (const auto& v: myAC.get()) { } // it involve not const get method
  30. }
  31. return 0;
  32. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
A::get()
A::get()
use const reference to instance
A::get() const