Overloading operators : const vs non-const return type : any difference of performance?

前端 未结 3 2013
余生分开走
余生分开走 2021-02-08 18:58

If we go to the wikipedia article about C++ operators, we have as an example :

Addition : a + b -> T T::operator +(const T& b) const;

S

3条回答
  •  孤城傲影
    2021-02-08 19:25

    I would say don't ever implement operator + as member function. Just implement operator += which is definitely not const. Then you provide a global function which takes care about operator +, I think this is the most common way to do it.

    T& T::operator +=(const T& t)
    {
        // add t to object ...
        return *this;
    }
    
    T operator +(T t1, const T& t2)
    {
        t1 += t2
        return t1; // RVO will eliminate copy (or move constructor)
    }
    

提交回复
热议问题