c++operator-overloadingmovervaluefunction-call-operator

How do I use the `Function Call Operator` to load `rvalue` types to my object?


I have a class like this:

template<typename T>
class MyClass
{
    public:
        // ...
              T && operator()(uint64_t i, uint64_t j);  // I want to add a member function like this.
              T &  operator()(uint64_t i, uint64_t j);
        const T &  operator()(uint64_t i, uint64_t j) const;
        // ...
};

While I was revising the code, I realized that the stored object of type T is being copied every time it tries to set an object to an (i,j) position. I would like to use move semantics and avoid this unnecessary copying if it is possible? Is it possible to solve this by adding a third operator like in the code above?

My aim is to access a MyClass instance like this in the code:

MyClass<Element> myclass;
// ...
Element element;                        // 'Element' is movable.
// ...
myclass(2, 3) = std::move(element);     // 'element' is no longer needed, it can be moved.

How can I do this?


Solution

  • First of all you can't overload based on the return type. However, this is not your problem since you don't need extra overloads of the subscript operator.

    In order to avoid unnecessary copies and since class Element objects are movable, you could use std::swap instead of direct assignment.

    std::swap(myclass(2, 3), element);
    

    Since C++11 std::swap avoids the unnecessary copy because it uses move semantics.