#include <cstring>
#include <iostream>
using namespace std;
// Test for copy-ellision
// A is old school class with pass-by-const-ref operator=
class A
{
public:
static int n,d,c;
A() : ptr(0),size(0) {}
A(size_t sz) : size(sz)
{
n++;
ptr = new float[sz];
}
A(A const& src)
{
size = src.size;
n++;
ptr = new float[size];
c++;
memcpy(ptr,src.ptr,sizeof(float)*size);
}
A& operator=(A const& src)
{
if(this != &src)
{
size = src.size;
d++;
if(ptr) delete[] ptr;
n++;
ptr = new float[size];
c++;
memcpy(ptr,src.ptr,sizeof(float)*size);
}
return *this;
}
void operator()() { cout << "non-const call" << endl; }
~A()
{
d++;
if(ptr) delete[] ptr;
ptr = 0;
}
private:
float* ptr;
int size;
};
int A::n = 0;
int A::d = 0;
int A::c = 0;
// B is new school class with pass-by-value operator=
class B
{
public:
static int n,d,c;
B() : ptr(0),size(0) {}
B(size_t sz) : size(sz)
{
n++;
ptr = new float[sz];
}
B(B const& src)
{
size = src.size;
n++;
ptr = new float[size];
c++;
memcpy(ptr,src.ptr,sizeof(float)*size);
}
B& operator=(B src)
{
swap(src);
return *this;
}
void swap(B& src)
{
std::swap(size,src.size);
std::swap(ptr,src.ptr);
}
void operator()() { cout << "non-const call" << endl; }
~B()
{
d++;
if(ptr) delete[] ptr;
ptr = 0;
}
private:
float* ptr;
int size;
};
int B::n = 0;
int B::d = 0;
int B::c = 0;
A sort( A const& names)
{
A ret = names;
ret();
return ret;
}
B sort( B names)
{
names();
return names;
}
int main()
{
cout << "gcc " << __GNUC__ << "." << __GNUC_MINOR__<< endl;
{
A a;
A b(5);
a = b;
A c;
c = sort(a);
}
cout << "A new : " << A::n << endl;
cout << "A delete : " << A::d << endl;
cout << "A copy : " << A::c << endl;
cout << endl;
{
B a;
B b(5);
a = b;
B c;
c = sort(a);
}
cout << "B new : " << B::n << endl;
cout << "B delete : " << B::d << endl;
cout << "B copy : " << B::c << endl;
cout << endl;
}