fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // modified largely from
  5. // http://d...content-available-to-author-only...e.jp/toburau/20090722/1248283158
  6.  
  7. /*
  8. class Test {
  9. public:
  10. Test& operator=(const Test& rhs);
  11. };
  12. Test& Test::operator=(const Test& rhs)
  13. {
  14. if (this == &rhs) return *this; // *****
  15. };
  16. */
  17.  
  18. //-----------------------------------------------------
  19.  
  20. class Data
  21. {
  22. int num;
  23. public:
  24. Data(void) : num(0) { }
  25. Data(int _num) : num(_num) { }
  26. Data(const Data &rhs) {
  27. cout << "copy constructor is called" << endl;
  28. num = rhs.num;
  29. }
  30. void show(void) {
  31. cout << num << endl;
  32. }
  33. };
  34.  
  35. class CopyTest {
  36. Data *m_pData;
  37. public:
  38. CopyTest(void) {
  39. m_pData = new Data(0);
  40. }
  41. CopyTest(int _num) {
  42. m_pData = new Data(_num);
  43. }
  44. void show(void) {
  45. m_pData->show();
  46. }
  47. CopyTest& operator=(const CopyTest& rhs);
  48. };
  49.  
  50. CopyTest& CopyTest::operator=(const CopyTest& rhs) /*****/
  51. {
  52. Data *p = m_pData;
  53. // m_pData = new Data(*rhs.m_pData); // case 0 // OK // copy constructor is called
  54. // m_pData = new Data(*(rhs.m_pData)); // case 1 // OK
  55. m_pData = new Data(*(rhs).m_pData)); // case 2 // NG
  56. delete p;
  57. return *this;
  58. }
  59.  
  60.  
  61. int main() {
  62. CopyTest cpyObjA, cpyObjB(31);
  63.  
  64. cpyObjA.show();
  65. cpyObjB.show();
  66.  
  67. cout << "## after" << endl;
  68. cpyObjA = cpyObjB;
  69. cpyObjA.show();
  70. cpyObjB.show();
  71.  
  72. return 0;
  73. }
Compilation error #stdin compilation error #stdout 0s 3428KB
stdin
Standard input is empty
compilation info
prog.cpp: In member function ‘CopyTest& CopyTest::operator=(const CopyTest&)’:
prog.cpp:55:36: error: expected ‘;’ before ‘)’ token
  m_pData = new Data(*(rhs).m_pData)); // case 2 // NG
                                    ^
stdout
Standard output is empty