C++ & Swap/Copy 应用于 Point 结构

C++ & Swap/Copy applied to a Point struct

我写了一个 Point 结构,我用它来模拟 n 体问题。我发现很难完全理解和实施复制和交换习惯用法并使其适应我的需求,主要是速度。我这样做正确吗?在 C++17 中会有所不同吗?

#pragma once
#include <algorithm>

struct Point
{
  double x, y, z;

  explicit Point(double X = 0, double Y = 0, double Z = 0) : x(X), y(Y), z(Z) {}
  void swap(Point&, Point&);

  inline bool operator==(Point b) const { return (x == b.x && y == b.y && z == b.z); }
  inline bool operator!=(Point b) const { return (x != b.x || y != b.y || z != b.z); }

  Point& operator=(Point&);
  Point& operator+(Point&) const;
  Point& operator-(Point&) const;
  inline double operator*(Point& b) const { return b.x*x + b.y*y + b.z*z; } // Dot product
  Point& operator%(Point&) const; // % = Cross product

  inline Point& operator+=(Point& b) { return *this = *this + b; }
  inline Point& operator-=(Point& b) { return *this = *this - b; }
  inline Point& operator%=(Point& b) { return *this = *this % b; }

  Point& operator*(double) const;
  Point& operator/(double) const;

  inline Point& operator*=(double k) { return *this = *this * k; }
  inline Point& operator/=(double k) { return *this = *this / k; }
};

std::ostream &operator<<(std::ostream &os, const Point& a) {
   os << "("  << a.x << ", " << a.y << ", " << a.z << ")";
   return os;
}

void Point::swap(Point& a, Point& b) {
    std::swap(a.x, b.x);
    std::swap(a.y, b.y);
    std::swap(a.z, b.z);
}

Point& Point::operator=(Point& b) {
  swap(*this, b);
  return *this;
}

Point& Point::operator+(Point& b) const {
  Point *p = new Point(x + b.x, y + b.y, z + b.z);
  return *p;
}

Point& Point::operator-(Point& b) const {
  Point *p = new Point(x - b.x, y - b.y, z - b.z);
  return *p;
}

Point& Point::operator%(Point& b) const {
  Point *p = new Point(
      y*b.z - z*b.y,
      z*b.x - x*b.z,
      x*b.y - y*b.x
  );

  return *p;
}

Point& Point::operator*(double k) const {
  Point *p = new Point(k*x, k*y, k*z);
  return *p;
}

Point& Point::operator/(double k) const {
  Point *p = new Point(x/k, y/k, z/k);
  return *p;
}

copy/swap-ideom 实际上复制了 swap() 的值。你的 "adaptation" 只是 swap()s。 copy/swap-ideom 的正确使用看起来像这样:

Point& Point::operator= (Point other) { // note: by value, i.e., already copied
    this->swap(other);
    return *this;
}

(当然,这也假设你的 swap() 函数是一个成员,只接受一个额外的参数: 已经是一个可以交换的对象)。

如果速度是您最关心的问题,copy/swap-ideom 可能不是特别适合 Point 的情况:复制操作本质上是微不足道的。与相对复杂的操作相比,交换值是非常合理的,例如通过 std::vector 复制一个旧数组,其中交换操作除了可能复制多个值和一些分配操作外,只相当于一些指针交换。也就是说,您的 Point 分配可能最好只分配所有成员:

Point& Point::operator= (Point const& other) { // note: no copy...
    this->x = other.x;
    this->y = other.y;
    this->z = other.z;
    return *this;
}

正如评论中指出的那样,您还应该使用new分配新的Point对象:C++不是Java或 C#!您可以只在堆栈上创建一个不需要来自堆的对象,例如:

Point Point::operator+ (Point const& other) const {
    return Point(this->x + other.x, this->y + other.y, this->z + other.z);
}