fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. class T
  5. {
  6. public:
  7. T(const std::string& name): name_(name), copy_(0){}
  8. T(const T& rhs)
  9. : name_(rhs.name_), copy_(rhs.copy_)
  10. {
  11. copy_++;
  12. }
  13.  
  14. void op(){ std::cout << name_ << "-copy: " << copy_ << std::endl; }
  15. private:
  16. int copy_;
  17. std::string name_;
  18. };
  19.  
  20. T op1(const T& val) // pass by const reference
  21. {
  22. std::cout << "op1" << std::endl;
  23. T tmp(val); //copy ctor
  24. tmp.op();
  25. return tmp;
  26. }
  27.  
  28. T op2(T val) // pass by value
  29. {
  30. std::cout << "op2" << std::endl;
  31. val.op();
  32. return val;
  33. }
  34.  
  35. int main( int argc, char* argv[] )
  36. {
  37. T t("lvalue");
  38.  
  39. op1(t).op();
  40. op1(T("rvalue")).op();
  41.  
  42. op2(t).op();
  43. op2(T("rvalue")).op();
  44.  
  45. return 0;
  46. }
Success #stdin #stdout 0.01s 2816KB
stdin
Standard input is empty
stdout
op1
lvalue-copy: 1
lvalue-copy: 1
op1
rvalue-copy: 1
rvalue-copy: 1
op2
lvalue-copy: 1
lvalue-copy: 2
op2
rvalue-copy: 0
rvalue-copy: 1