Temporaries optimization in chaining operator

Viewed 68

I have an Array class which is expensive to construct a new instance. I defined operator+ for it to be able to chain up like this.

class Array
{
public:
    //...
    Array& operator+=(Array const&);
    Array operator+(Array const&);
};

Array a, b, c, d;
Array e = a + b + c + d; //a+b->Temp, Temp+c->Temp2, Temp2+d->e, BAD!

I want it to be able to use operator+= which saves the cost of constructing a new instance, instead of using operator+ which will construct a new instance. I tried using reference qualifier like this:

Array operator+(Array const&) &;
Array& operator+(Array const&) &&; //call += internally

But after Temp+c->Temp, Temp+d will call operator+() & which still create new instance.

EDIT: I tried

Array&& operator+(Array const&) &&
{
    //...
    return std::move(*this);
}

Which seems to work, but will it dangle? Because Array e = a + b + c + d; will call move constructor to move the final temporary into e and I can do some tricks in the move constructor to prevent the resource being freed when the temporary is destoried after the expression, if I am correct.

0 Answers
Related