fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. class Verbose
  5. {
  6. public:
  7. friend std::ostream& operator<<(std::ostream& os, const Verbose& v) ;
  8.  
  9. Verbose() : _id(_nextID++)
  10. { std::cout << *this << " constructed via default constructor.\n" ; }
  11.  
  12. Verbose(const std::string& s) : _id(_nextID++), _data(s)
  13. { std::cout << *this << " constructed via std::string constructor.\n" ; }
  14.  
  15. Verbose( const Verbose& v ) : _id(_nextID++), _data(v._data)
  16. { std::cout << *this << " constructed via copy constructor from " << v << ".\n" ; }
  17.  
  18. ~Verbose()
  19. {
  20. std::cout << *this << " destroyed.\n" ;
  21. }
  22.  
  23. Verbose operator=(const Verbose& v)
  24. {
  25. std::cout << *this << " = " << v << '\n' ;
  26.  
  27. _data = v._data ;
  28.  
  29. return *this ;
  30. }
  31.  
  32. private:
  33.  
  34. const unsigned _id ;
  35. std::string _data ;
  36.  
  37. static unsigned _nextID ;
  38. };
  39.  
  40. std::ostream& operator<<(std::ostream& os, const Verbose& v )
  41. {
  42. return os << "Verbose #" << v._id << " (\"" << v._data << "\")" ;
  43. }
  44.  
  45. unsigned Verbose::_nextID = 1 ;
  46.  
  47. int main()
  48. {
  49. Verbose motto1("The devil takes care of his own"); // Verbose #1
  50. Verbose motto2; // Verbose #2
  51. Verbose motto3; // Verbose #3
  52.  
  53. std::cout << "---- Before temporary expression ----\n" ;
  54. (motto1 = motto2) = motto3 ; // Verbose #4 and #5 are temporaries.
  55. std::cout << "---- After temporary expression ----\n" ;
  56.  
  57. return 0;
  58. }
Success #stdin #stdout 0s 3032KB
stdin
Standard input is empty
stdout
Verbose #1 ("The devil takes care of his own") constructed via std::string constructor.
Verbose #2 ("") constructed via default constructor.
Verbose #3 ("") constructed via default constructor.
---- Before temporary expression ----
Verbose #1 ("The devil takes care of his own") = Verbose #2 ("")
Verbose #4 ("") constructed via copy constructor from Verbose #1 ("").
Verbose #4 ("") = Verbose #3 ("")
Verbose #5 ("") constructed via copy constructor from Verbose #4 ("").
Verbose #5 ("") destroyed.
Verbose #4 ("") destroyed.
---- After temporary expression  ----
Verbose #3 ("") destroyed.
Verbose #2 ("") destroyed.
Verbose #1 ("") destroyed.