C++ 复制构造函数错误地接受参数

标签 c++ copy-constructor

我有以下行为异常的代码。到目前为止我理解的流程是,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;
}

最佳答案

你的程序调用了undefined behavior (UB)。当您的构造函数完成时:

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

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

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

关于C++ 复制构造函数错误地接受参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65377448/

相关文章:

c++ - 避免在 Visual C++ 2008 中跳出 block

c++ - 如何保留一个类的实例列表?

c++ - Char数据类型和while循环

c++ - 调用复制构造函数时会发生什么类型的初始化?

c++ - 使用已删除的函数 std::unique_ptr

c++ - Malloc Memset 这个用法对吗?

c++ - 原子变量的 vector (数组)

c++ - RValue、模板解析和复制构造函数(在 Visual C++ 2010 中)

c++ - 在 C++ 中为 HashMap 编写有效的复制构造函数

c++ - cout 逆序打印