簡體   English   中英

C++ 復制構造函數錯誤地接受參數

[英]C++ copy constructor incorrectly takes argument

我有以下行為奇怪的代碼。 到目前為止我理解的流程是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;
}

您的程序調用未定義的行為(UB)。 當您的構造函數完成時:

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

指針ptr指向一個不再存在的局部變量len ptr現在懸空,任何取消引用它的嘗試都會調用 UB。

你的程序可以做任何事情。 您還可以看到一些奇怪的結果,例如添加int x = 3導致您的程序“行為正確”。 不要擔心為什么會發生這種情況,這只是UB的結果。

這是一個常見錯誤(盡管這是一個奇怪的版本)。

這段代碼是錯誤的

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

ptr指向lenlen是一個局部變量。 它在構造函數退出時被銷毀。 這意味着您有一個指向不再存在的 object 的指針。 有時這稱為懸空指針

然后稍后在代碼中使用此指針

cout<<"[origin] *ptr="<<*obj.ptr<<endl;

由於指針現在無效,因此效果是不可預測的。

使指針變得困難的許多事情之一是指針的生命周期和它所指向的生命周期根本沒有任何聯系。 您需要確保您的指針始終指向仍然“活動”的對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM