Advertisement
Dinosawer

Vivrefs 2

Jan 17th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. class Thingy{
  2. private:
  3. std::vector<int> stuff; // stuff
  4. public:
  5. Thingy(){
  6. stuff = {1,2,3};
  7. }
  8. std::vector<int> getStuff(){
  9. return stuff;
  10. }
  11. std::vector<int>& getStuffRef(){
  12. return stuff;
  13. }
  14. void printstuff(){
  15. for (int i = 0; i < stuff.size(); ++i){
  16. printf("%d, ", stuff[i]);
  17. }
  18. printf("\n");
  19. }
  20. };
  21.  
  22. // actual code
  23. Thingy thing = Thingy();
  24. std::vector<int> theStuff = thing.getStuff();
  25. theStuff.append(4);
  26. thing.printstuff();
  27. /* this will print
  28. 1, 2, 3,
  29. because we got a copy of the vector, not a reference, so the original wasn't changed by our append */
  30.  
  31. theStuff = thing.getStuffRef();
  32. theStuff.append(4);
  33. thing.printstuff();
  34. /* this will print
  35. 1, 2, 3, 4,
  36. because we got a reference to the vector in the object, so the original WAS changed by our append */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement