以下代码中的复制构造函数中的意外输出

时间:2014-09-25 20:12:57

标签: c++

#include < iostream >

using namespace std;

class A
{

      public:
           int x;
           A(int i)
           {

            x= i;
            cout<<"Constructor is Called "<<x<<endl;
          }
          ~A()
           {
            cout<<"destructor is Called "<<x<<endl;
           }

          A(const A &a)
          {
                cout<<"in copy constructor a.x = "<<a.x<<endl;
                cout<<" x = "<<x<<endl;
          }
      };

      const A &fun(int i)
      {
          cout<<"in Fun"<<endl;
          A t(i+1);
          return(t);
      }

     main()
     {
          A *gg = new A(5);
          A t = fun(2);
     }

输出结果为:

Constructor is Called 5  
in Fun  
Constructor is Called 3  
destructor is Called 3  
in copy constructor a.x = 0  
x = 4067272

为什么是a.x=0x= 4067272

1 个答案:

答案 0 :(得分:0)

添加代码以初始化复制构造函数中的x

      A(const A &a) : x(a.x)
                  //^^^^^^^^^^^^^^^ Missing code
      {
            cout<<"in copy constructor a.x = "<<a.x<<endl;
            cout<<" x = "<<x<<endl;
      }

另外,

fun返回对局部变量的引用。从fun返回后,引用无效。当您使用A t = fun(2);时,您正在进入UB区域。你不能假设任何合理的东西。

您可以通过从fun而不是const&返回对象来解决此问题。

  A fun(int i)
  {
      cout<<"in Fun"<<endl;
      A t(i+1);
      return(t);
  }