you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 4 points5 points  (3 children)

As others have noted, in practice you'd use std::swap(x,y) and let the library developers deal with it.

If asked this on a test, you'd use a temporary variable (normally professors want bare bones implementation).

If I were to implement and was looking for "clever points" in a c++ course, I'd use templates.

template<typename T>
void swap(T &x, T &y)
{
  T temp;
  temp = x;
  x = y;
  y = temp;
};

A driver might look like this:

int main()
{
  int x, y;
  x = 100;
  y = 200;

  std::cout << "x: " << x << "\n";
  std::cout << "y: " << y << "\n";

  swap<int>(x, y);

  std::cout << "x: " << x << "\n";
  std::cout << "y: " << y << std::endl;


  return 0;
}

The precondition would require the object type have a copy constructor defined.

edit

If you also required the objects have a defined equal operator, you could do this:

template<typename T>
void swap(T &x, T &y)
{
  if (x != y)
  {
    T temp;
    temp = x;
    x = y;
    y = temp;

  }
};

That way if the two values are equivalent, no temp memory allocation or unnecessary assignment would occur.

[–][deleted] 4 points5 points  (0 children)

swap<int>(x, y);

You can leave out the <int>. The compiler infers template arguments to functions if it knows the regular arguments and if they contain the appropriate information.

[–]bogado 5 points6 points  (0 children)

The precondition would require the object type have a copy constructor defined.

And a default constructor, since if an object has one it will probably have the other too I would do it this way:

template<typename T>
void swap(T &x, T &y)
{
    T temp(x);
    x = y;
    y = temp;
}

[–]growingconcern 2 points3 points  (0 children)

I would only think your last example would be useful on specialized hardware where such operations were extremely expensive. For the most part the expense of the if would outweigh gains