我有一个类,它本质上是一个带有标签内容的数组,我想为它定义一些运算符。我想以这样一种方式来改变类中元素的数量很容易,因为我希望未来的用户会改变跟踪的变量,但我也想确保类上的基本算术运算是尽可能高效。
我可以看到两种实现运算符的方式。以一个Vector2D类为例:
struct Vector2D {
    //members
      const static int nElem = 2;
      double x;
      double y;
    //Constructors
      Vector2D() {}          
      Vector2D(double X, double Y) : x(X), y(Y) {}
    //Operators
      double& operator[] (int index) {
        switch(index) { 
          case 0:
            return x;
          case 1:
            return y;
          default:
            return std::out_of_range ("Oops");
        }
      }
    // Option 1: operator+ by constructing result
    Vector2D operator+ (const Vector2D & rhs) const {
      return Vector2D(x + rhs.x, y+rhs.y);
    }
    // Option 2: operator+ using loop and [] operator
    Vector2D operator+ (const Vector2D & rhs) const {
      Vector2D result;
      for(int i = 0; i < nElem; i++)
        result[i] = (*this)[i] + rhs[i];
      return result;
    }
};
假设我使用 -03 优化,这两种实现之间会有什么区别operator+吗?我的理解是,由于默认Vector2D构造函数没有代码主体,并且类内容是默认数据类型,因此选项 2 中没有额外的开销,用于result在设置其成员之前调用默认构造函数。我希望两者是等价的,但我对自己的知识没有足够的信心来确定。