1. #include <iostream>
  2. class A
  3. {
  4. public:
  5. A(const char* cname) : name(cname)
  6. {
  7. std::cout << "constructing " << cname << std::endl;
  8. }
  9. ~A(){
  10. std::cout << "destructing " << name.c_str() << std::endl;
  11. }
  12. A(A const& a)
  13. {
  14. if (name.empty()) name = "*tmp copy*";
  15. std::cout << "creating " << name.c_str() << " by copying " << a.name.c_str() << std::endl;
  16. }
  17. A& operator=(A const& a)
  18. {
  19. std::cout << "assignment ( " << name.c_str() << " = " << a.name.c_str() << " )"<< std::endl;
  20. return *this;
  21. }
  22. std::string name;
  23. };
  24. A foo()
  25. {
  26. A b("b");
  27. return b;
  28. }
  29. int main()
  30. {
  31. A a("a");
  32. a = foo();
  33. }

output without NRVO:

constructing a

constructing b

creating *tmp copy* by copying b

destructing b

assignment ( a = *tmp copy* )

destructing *tmp copy*

destructing a

output with NRVO:

constructing a

constructing b

assignment ( a = b )

destructing b

destructing a