#include <iostream>
#include <list>
#include <pthread.h>
/*
* test copy constructors and copy assignment
* g++ -Wall copyctor.cc -o copyctor
* ./copyctor
* valgrind -v --leak-check=full --show-reachable=yes ./copyctor
*/
using namespace std;
class CopyCtor {
private:
pthread_mutex_t pMutex;
int * passed_in;
int * created_1;
int * created_2;
list<int> functions;
public:
CopyCtor();
CopyCtor(int * passedin);
CopyCtor(const CopyCtor &cc); // copy constructor
CopyCtor& operator=(const CopyCtor &cc); // copy assignment
~CopyCtor();
};
CopyCtor::CopyCtor(): passed_in(NULL), created_1(NULL), created_2(NULL) {}
// Ctor
CopyCtor::CopyCtor(int * passedin): passed_in(passedin) {
pthread_mutex_init(&pMutex, NULL);
created_1 = new int(1);
created_2 = new int(2);
cout << "CopyCtor::ctor: passed_in " << *passed_in << "," << passed_in << ", created_1: " << *created_1
<< "," << created_1 << ", created_2: " << *created_2 << "," << created_2 << endl;
}
// copy constructor
CopyCtor::CopyCtor(const CopyCtor & cc) {
// want to get a new lock
pthread_mutex_init(&pMutex, NULL);
pthread_mutex_lock(&pMutex);
//if (passed_in)
// delete(passed_in);
passed_in = cc.passed_in;
/*if (created_1)
delete created_1;
if (created_2)
delete created_2;*/
created_1 = new int(*cc.created_1);
created_2 = new int(*cc.created_2);
cout << "CopyCtor::copy ctor: passed_in " << *passed_in << "," << passed_in << ", created_1: " << *created_1
<< "," << created_1 << ", created_2: " << *created_2 << "," << created_2 << endl;
pthread_mutex_unlock(&pMutex);
}
// copy assignment operator
CopyCtor & CopyCtor::operator=(const CopyCtor& cc)
{
if (this != &cc) {
// want to get a new lock
pthread_mutex_init(&pMutex, NULL);
pthread_mutex_lock(&pMutex);
//if (passed_in)
// delete(passed_in);
passed_in = cc.passed_in;
if (created_1)
delete created_1;
if (created_2)
delete created_2;
created_1 = new int(*cc.created_1);
created_2 = new int(*cc.created_2);
cout << "CopyCtor::operator=: passed_in " << *passed_in << "," << passed_in << ", created_1: " << *created_1
<< "," << created_1 << ", created_2: " << *created_2 << "," << created_2 << endl;
pthread_mutex_unlock(&pMutex);
} else {
pthread_mutex_lock(&pMutex);
cout << "CopyCtor::operator=: this == &cc: passed_in " << *passed_in << "," << passed_in
<< ", created_1: " << *created_1
<< "," << created_1 << ", created_2: " << *created_2 << "," << created_2 << endl;
pthread_mutex_unlock(&pMutex);
}
return *this;
}
CopyCtor::~CopyCtor()
{
cout << "~CopyCtor" << endl;
delete created_1;
delete created_2;
}
int main()
{
int first = -1;
int second = -2;
CopyCtor *cc = new CopyCtor(&first);
CopyCtor *cd = new CopyCtor(&second);
*cd = *cc;
CopyCtor *ce;
ce = new CopyCtor(*cd);
CopyCtor cf = *ce;
cf = cf;
delete(ce);
delete(cc);
delete(cd);
}