簡體   English   中英

將退出重載的賦值運算符,調用析構函數以刪除對象

[英]will exiting the overloaded assignment operator invoke destructor to delete the object

在c ++中,以下代碼。

#include <iostream>
using namespace std;

class Object {

public:
   Object(int id){
     cout << "Construct(" << id << ")" << endl;
     m_id = id;
   }

   Object(const Object& obj){
      cout << "Copy-construct(" << obj.m_id << ")" << endl;
      m_id = obj.m_id;
   }

   Object& operator=(const Object& obj){
      cout << m_id << " = " << obj.m_id << endl;
      m_id = obj.m_id;
      return *this;
   }

   ~Object(){
       cout << "Destruct(" << m_id << ")" << endl;
   }
private:
   int m_id;

};

int main(){
   Object v1(1);
   cout << "( a )" << endl;
   Object v2(2);
   v2 = v1;
}

和相關的輸出

Construct(1)
( a )
Construct(2)
2 = 1

為什么在=運算符之后不調用destructor obj in operator =obj in operator =應該退出作用域並應該對其自身調用destructor 是不是

不會。在范圍內未創建“ obj”,因此不會在范圍內銷毀它。 這是一個參數,它是一個參考。 實際對象在其他地方。

暫無
暫無

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

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