2

Consider a point class, with declarations like:

// Point.h
class Point {
    public:
        Point();                           // Default constructor
        Point(const Point & p);            // Copy constructor
        Point & operator=(Point source);   // Copy assignment operator, needs implemented
        ~Point();                          // Destructor
    // ...
    private:
        double m_x;                        // X coordinate
        double m_y;                        // Y coordinate
};

For the homework, the only thing I have left to implement is the copy assignment operator.
The canonical answer for how to do this is the copy-and-swap idiom.

Using the swap function for copy assignment solves one problem and creates another (how to implement the swap function).

While I don't feel a need to provide a swap function, I wouldn't know how best to implement swap anyway. Is it to specialize std::swap? I know about neither namespaces nor template specialization yet.

Formally, my question is two-fold:

  1. How should copy assignment be implemented? If it uses a swap function, how should I implement that?
  2. In the wild, would I simply not write the Big Three members, as the Point class is simply two numbers? Will the compiler write the operations correctly and optimally?
Community
  • 1
  • 1
Prashant Kumar
  • 20,069
  • 14
  • 47
  • 63

2 Answers2

2
  1. Copy-and-swap is best practice. If you don't want to override std::swap because you're unfamiliar with templates, then you can also write a swap_points function or a Point::swap(Point &other) member function.

    The implementation of that (member) function is very simple: just call std::swap on all of the members.

  2. Yes, implementing the Big Three yourself for this class is really an academic exercise.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
2

The naive works here, because Point doesn't manage any resources.
Simply copying the double values won't throw an exception, so this code is exception-safe (and in turn is self-assignment safe).

// Point.cpp

Point & operator=(Point source);
    m_x = source.m_x;
    m_y = source.m_y;

    return *this;
}
Prashant Kumar
  • 20,069
  • 14
  • 47
  • 63