IrreverentMallard
IrreverentMallard

Reputation: 11

Overloading swap function in C++ class

I am trying to implement a swap function, that overrides the copy constructor and ultimately will allow me to use the equal '=' operator. The issue is when testing my swap function I get junk values for everything in other(isNeg is a bool, digits is an unsiged int* array, and numDigits is the size of digits.
A ReallyLongInt is an Unsigned Int* array of size numDigits, I have thoroughly tested my constructors and they work for both Strings and long longs.

Here is the declaration (ReallyLongInt.cc) :

void ReallyLongInt::swap(ReallyLongInt other)
{

  //Sets temporary values to equal others values
  unsigned int* temp = new unsigned int[this->numDigits];

  std::swap(this->digits, other.digits);
  std::swap(this->numDigits, other.numDigits);
  std::swap(this->isNeg, other.isNeg);

 }

and my main which I use to test (main.cc)

#include "ReallyLongInt.h"
#include <iostream>


using namespace std;


int main(int argc, char** argv){
  string a = "56789";
  long long b = 123456;


  ReallyLongInt x = ReallyLongInt(a);
  ReallyLongInt y = ReallyLongInt(b);
  cout<<"a: "<<x<<endl;
  cout<<"b: "<<y<<endl;
  y.swap(x);

  cout <<"b after swapping with a:  "<< y <<endl;


}

I believe the problem lies in the value I pass to my swap call

y.swap(x)

but when I run the code the size of this->numDigits is junk, and I get a segFault because of this number interfering with my print function.

Upvotes: 0

Views: 1063

Answers (2)

Jive Dadson
Jive Dadson

Reputation: 17036

As aschepler says,

void ReallyLongInt::swap(ReallyLongInt& other);

Also, it is a mistake to use new that way in your swap function. You allocate a new structure then abandon it. Standard C++ does not do garbage collection, so the temp object is a memory leak.

You can do better than trying to repair this code. Here is a thread that shows the best practice for specializing swap, including the copy-and-swap idiom. Enjoy.

http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom

Upvotes: 0

aschepler
aschepler

Reputation: 72401

void ReallyLongInt::swap(ReallyLongInt other)

Any function that specifies a parameter "passed by value" means that a fresh copy will be initialized every time the function is called. So when you call y.swap(x), you are modifying a function-local variable other, and not the object x like you intended.

To allow a function to modify the object passed in, you should use a reference parameter instead:

void ReallyLongInt::swap(ReallyLongInt& other);

By the way, the normal form of swap which some standard functions check for is a non-member function taking two arguments. So outside of the class:

void swap(ReallyLongInt& a, ReallyLongInt& b);

If you like, you can implement the non-member swap in terms of the member swap.

Upvotes: 1

Related Questions