Implementing swap()



Now that our Glib::Objects and Gtk::Widgets are movable, so they can be
placed in standard containers, I guess we should implement swap() so the
standard containers can use that too. And maybe it's just generally good
practice to provide a swap() for all classes. Stop me at this point if
I'm wrong about that.


If we do want to provide swap() for these classes, I'd like to agree
about how best to implement them:

We already have swap() for our boxed type classes, such as Gdk::Color.
We implement a member swap():

void Color::swap(Color& other) noexcept
{
  GdkColor *const temp = gobject_;
  gobject_ = other.gobject_;
  other.gobject_ = temp;
}

and we implement a standalone swap in our namespace, so that std::swap()
can use it. (See http://www.cplusplus.com/reference/utility/swap/ )
We implement that standalone swap with our member swap():

inline void swap(Color& lhs, Color& rhs) noexcept
  { lhs.swap(rhs); }


At the moment we are using the member swap in our move assignment
operator and copy assignment operators (operator=):

Color& Color::operator=(Color&& other) noexcept
{
  Color temp(other);
  swap(temp);
  return *this;
}

Color& Color::operator=(const Color& other)
{
  Color temp(other);
  swap(temp);
  return *this;
}

The member swap() is obviously useful for those operator=()
implementations, though I guess swap(*this, temp) would work too.
But the member swap() isn't inline so our standalone swap() isn't as
efficient as it could be.

So:
Should we make our member swap() methods inline?
Should we not have member swap() methods and just use our standalone
swap() functions?

And, should we implement swap() using std::swap() on the member
variables, or even std::move() on the member variables?

-- 
Murray Cumming
murrayc murrayc com
www.murrayc.com




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]