assignment operator vs. copy constructor C++

前端 未结 3 1312
我在风中等你
我在风中等你 2021-02-01 05:34

I have the following code to test out my understanding of basic pointers in C++:

// Integer.cpp
#include \"Integer.h\"
Integer::Integer()
{
  value = new int;
           


        
3条回答
  •  旧巷少年郎
    2021-02-01 06:37

    The copy constructor is not used during assignment. Copy constructor in your case is used when passing arguments to displayInteger function. The second parameter is passed by value, meaning that it is initailized by copy contructor.

    Your version of copy constructor performs deep copying of data owned by the class (just like your assignment operator does). So, everything works correctly with your version of copy constructor.

    If you remove your own copy constructor, the compiler will generate one for you implicitly. The compiler-generated copy constructor will perform shallow copying of the object. This will violate the "Rule of Three" and destroy the functionality of your class, which is exactly what you observe in your experiment. Basically, the first call to displayInteger damages your intVal1 object and the second call to displayInteger damages your intVal2 object. After that both of your objects are broken, which is why the third displayInteger call displays garbage.

    If you change the declaration of displayInteger to

    void displayInteger( char* str, const Integer &intObj )
    

    your code will "work" even without an explicit copy constructor. But it is not a good idea to ignore the "Rule of Three" in any case. A class implemented in this way either has to obey the "Rule of Three" or has to be made non-copyable.

提交回复
热议问题