assignment operator vs. copy constructor C++

前端 未结 3 1283
我在风中等你
我在风中等你 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:34

    Think about this call:

    displayInteger( "intVal1", intVal1 );
    

    You are creating a copy of intVal1 into the intObj parameter of displayInteger:

    void displayInteger( char* str, Integer intObj )
    {
      cout << str << " is " << intObj.getInteger() << endl;
    }
    

    That copy will be pointing to the same int that intVal1 is. When displayInteger returns, intObj is destroyed, which will cause the int to be destroyed, and the pointer in intVal1 to be pointing to an invalid object. At that point all bets are off (A.K.A. undefined behavior) if you try to access the value. A similar thing happens for intVal2.

    At a more general level, by removing the copy constructor, you are violating the Rule of Three, which typically leads to these kinds of problems.

提交回复
热议问题