Search code examples
c++argumentspass-by-referencetemporary-objects

Passing temporary objects by reference


I have two classes: Circle and Dot

Class Circle contains a Dot, and Dot contains an int. Circle has a getDot() function, and Dot has a lessThan(Dot& ) function.

I want to sort an array of Circles, elems[], by the int values inside Dot. If I have a Circle circ that I want to compare to some value in the array, I essentially need a line that does the following:

elems[0].getDot().lessThan(circ.getDot())

But it won't compile... I can fix the issue by having a temporary

Dot dt = circ.getDot()

and passing

elems[0].getDot().lessThan(dt)

but this seems like unnecessary copying. Is there a more efficient way to solve this?

Unfortunately, I am limited to using lessThan(dot&) for comparison, but I can modify the contents of it.

The compiler error is: error: invalid initialization of non-const reference of type ‘Dot&’ from an rvalue of type ‘Dot’ cout<


Solution

  • example:

    #include <vector>
    #include <algorithm>
    
    struct Dot
    {
        Dot(int i) : value_(i) {}
        bool lessThan(Dot const& other) const
        {
            return value_ < other.value_;
        }
    
        int value_;
    };
    
    struct Circle
    {
        Circle(Dot dot = Dot(0))
        : dot_(dot)
        {
        }
    
        const Dot& getDot() const { return dot_; }
    
        Dot dot_;
    };
    
    
    void sortCircles(std::vector<Circle>& circles)
    {
        auto order = [](Circle const& l, Circle const& r)
        {
            return l.getDot().lessThan(r.getDot());
        };
        std::sort(circles.begin(), circles.end(), order);
    }