copy constructor/ copy operator=

Hi,
I have the following sample code and result of execution as below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 
  // header
  #include <stdio.h>
  class Temp
  {
  public: 
  // simulate compiler-auto-generated default constructors, destructor, etc.
    inline Temp() { ::printf("Enter %s()\n", __func__);}
    inline ~Temp() {::printf("Enter %s()\n", __func__);}
    inline Temp(const Temp& rhs) { ::printf("Enter copy %s(const Temp& rhs)\n", __func__);}
    inline Temp& operator= (const Temp& rhs) {::printf("Enter %s()\n", __func__);}
  };

  // caller
  int main()
  {
    Temp e1;           // default constructor called
    {Temp e2(e1);}     // copy constructor called
    {Temp e2 = e1;}    // copy constructor called ?? not operator=
    return 0;
  }



Result of Running ...
Enter Temp()
Enter copy Temp(const Temp& rhs)
Enter ~Temp()
Enter copy Temp(const Temp& rhs)
Enter ~Temp()
Enter ~Temp()

Questions:
1. I thought Temp e2 = e1 would call operator =, but actually called copy constructor. I am not sure why and I was wondering what would be the difference between
Temp e2 = e1; and Temp e2(e1); call?

2. Is there any way that we can force Temp e1 object to be cleared/deleted/free before the end block "}" of main() is reached?

Thanks a lot!!!
1) It would never call operator=. Just like '*' is used for both multiplication and dereferencing, the character '=' is used for more than one purpose.

The difference between the various forms of copy construction is about the permissible implicit conversions: Temp e2(e1);allows everything, Temp e2 = e1; doesn't call explicit constructors, Temp e2{e1}; prohibits narrowing conversions. But in your case, e1 has the type Temp. No conversions are needed, and there is no difference.

2) Yes, you can call destructors directly. However, the end of main() will call e1's destructor again and that's an error (unless you placement-new e1 back into existence before letting main() end.. but you don't want to go there)
Last edited on
Hi Cubbi,

Thanks for your help/answer! :D

Got it.
Thanks,




Hi Cubbi,

Sorry. May I confirm again..

Is Temp e2(e1); -> allows implicit conversions or prohibits it?

Thanks!
All of them allow some implicit conversions. The function-call form allows the most
Last edited on
Topic archived. No new replies allowed.