开发者

allocating memory when overriding + operator in c++

I am creating a custom obj开发者_如何学Cect and overriding the + operator. I am return a new object of the same type. Is it bad practise to allocate memory inside this method? because I then I will need to delete the memory out of scope.


Yes, without further information, it is bad.

Usually you do:

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(...)
     }
}

That said, you could return a unique_ptr if you really had to allocate dynamically.


There's a nice example of overloading operator+ to return a new instance of the object as the result, without dynamic allocation.

The source is here, with a lot of explanations on how to overload operators.

The example is this:

  // 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;
  }

It assumes you implemented operator+= and a copy constructor, if you don't have += - just put the assignment operations there directly. Read the link for more details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜