fork download
  1. #include <iostream>
  2. #include <iomanip>
  3.  
  4. class A {
  5. public:
  6. A() { std::cout << "ctor A" << std::hex << this << std::endl ; }
  7. A(const A&) { std::cout << "cctor A" << std::hex << this << std::endl ; }
  8. ~A() { std::cout << "dtor A" << std::hex << this << std::endl ; }
  9. } ;
  10.  
  11. class B {
  12. public:
  13. A f1() {
  14. std::cout << "before f2()" << std::endl ;
  15. const A& a = f2();
  16. std::cout << "after f2()" << std::endl ;
  17. /*Какие-то вычисления. Просто "return f2();", чтобы без лишних копирований, сделать не удасться.*/
  18. return a;
  19. }
  20. private:
  21. virtual const A& f2() {
  22. std::cout << "f2() create object a" << std::endl ;
  23. A a;
  24. std::cout << "f2() return reference for object a" << std::endl ;
  25. return a;
  26. }
  27. } ;
  28.  
  29.  
  30. int main()
  31. {
  32. B b ;
  33. b.f1() ;
  34. }
  35.  
Success #stdin #stdout 0s 3300KB
stdin
Standard input is empty
stdout
before f2()
f2() create object a
ctor A0xbfbea1ff
f2() return reference for object a
dtor A0xbfbea1ff
after f2()
cctor A0xbfbea1fe
dtor A0xbfbea1fe