首页 > 解决方案 > C++ 复制构造函数错误地接受参数

问题描述

我有以下行为奇怪的代码。到目前为止我理解的流程是,display(line);将调用复制构造函数Line::Line(const Line &obj),并将line传入的引用。但是cout<<"[origin] *ptr="<<*obj.ptr<<endl;将打印[origin] *ptr=32767而不是[origin] *ptr=10

更奇怪的是,如果我取消注释// int x=3;,它会正确打印,但我真的不知道为什么。

您可以在以下位置找到可执行代码:https ://www.onlinegdb.com/pjbPO0X1f

#include <iostream>
 
using namespace std;
 
class Line
{
   public:
      int getLength( void );
      Line( int len );
      Line( const Line &obj);

   private:
      int *ptr;
};
 
// constructor
Line::Line(int len)
{
    ptr=&len;
    cout<<"*ptr="<<(*ptr)<<endl;
}

// copy constructor
Line::Line(const Line &obj)
{
    // int x=3;
    cout<<"[origin] *ptr="<<*obj.ptr<<endl;
    ptr = new int;
    *ptr = *obj.ptr; // copy
}

int Line::getLength( void )
{
    return *ptr;
}
 
void display(Line obj)
{
   cout << "line=" << obj.getLength() <<endl;
}

int main( )
{
   Line line(10);
   display(line);
   return 0;
}

标签: c++copy-constructor

解决方案


您的程序调用未定义的行为(UB)。当您的构造函数完成时:

Line::Line(int len)
{
    ptr=&len;
    cout<<"*ptr="<<(*ptr)<<endl;
} // ptr is dangling

指针ptr指向一个len不再存在的局部变量。ptr现在悬空,并且任何取消引用它的尝试都会调用 UB。

你的程序可以做任何事情。您还可以看到一些奇怪的结果,例如添加int x = 3导致您的程序“行为正确”。不要担心为什么会发生这种情况,这只是UB的结果。


推荐阅读