首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 最佳實踐:用 operator+= 實現 operator+,提升效能與一致性

     編輯:關於C++

用戶定義類型中,x = x + y 與 x += y 無自動關聯。**三大運算符(+、=、+=)互不相關,需手動實現一致性**。

推薦模式:單獨形式委託賦值形式


class Rational {
public:
    Rational& operator+=(const Rational& rhs);
    Rational& operator-=(const Rational& rhs);
};
const Rational operator+(const Rational& lhs, const Rational& rhs) {
    return Rational(lhs) += rhs;
}
const Rational operator-(const Rational& lhs, const Rational& rhs) {
    return Rational(lhs) -= rhs;
}

優勢:

  1. 僅維護 +=/-=,單獨形式自動一致;
  2. 若賦值形式為 public,單獨形式無需友元;
  3. 可用模板自動生成單獨形式:

template<class T> const T operator+(const T& lhs, const T& rhs) {
    return T(lhs) += rhs;
}

效能三考量

  1. 賦值形式更高效:結果直接寫入左操作數,無臨時對象構造/析構開銷。
  2. 雙重提供,用戶選擇:result = a + b + c + d(易讀、可接受 80% 場景)vs result=a; result+=b; ...(極致效能)。語義保持一致。
  3. 實現技巧影響優化:return T(lhs) += rhs;(臨時對象)比 T result(lhs); return result += rhs;(命名對象)更易觸發編譯器**返回值優化 (RVO)**,尤其舊編譯器下更優。雖兩者開銷相近,未命名對象歷史上更易優化。

結語

庫設計者雙提供、應用開發者效能優先用賦值形式。**賦值形式是基石,單獨形式是語法糖**——守住這原則,代碼才健壯高效。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved