簡體   English   中英

在C ++中重寫+運算符時分配內存

[英]allocating memory when overriding + operator in c++

我正在創建一個自定義對象並覆蓋+運算符。 我將返回一個相同類型的新對象。 在此方法內分配內存是不好的做法嗎? 因為那時我將需要刪除超出范圍的內存。

是的,沒有更多信息,這很糟糕。

通常您會:

struct X
{
     int m_i;
     X(int i) : m_i(i) {  }

     X operator+(const X& another) const
     {
         return X(m_i + another.m_i); // note, not new X(...)
     }
}

也就是說,如果您確實必須動態分配,則可以返回unique_ptr。

有一個很好的例子,重載operator+可以返回對象的實例作為結果, 而不進行動態分配。

來源在這里 ,其中有許多有關如何重載運算符的說明。

例子是這樣的:

  // Add this instance's value to other, and return a new instance
  // with the result.
  const MyClass MyClass::operator+(const MyClass &other) const {
    return MyClass(*this) += other;
  }

假設您實現了operator+=和一個復制構造函數,如果您沒有+= -只需將賦值操作直接放在那里。 閱讀鏈接以獲取更多詳細信息。

暫無
暫無

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

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