#include <iostream>
#include <cstddef>
#include <utility>
class Test
{
public:
Test() : m_charArray( nullptr ), m_sizeOfArray( 0 )
{
std::cout << "[Test::default c'tor] Instance at 0x" << std::hex << this << std::dec << " default-constructed.\n";
}
// NOTE: charArray must be a null pointer or a pointer to a heap-allocated array because Test's destructor will attempt to delete [] it!
Test( char* charArray, std::size_t sizeOfArray ) : m_charArray( charArray ), m_sizeOfArray( sizeOfArray )
{
std::cout << "[Test::parametrizable c'tor] Instance at 0x" << std::hex << this << std::dec << " constructed with explicit values.\n";
}
Test( const Test& other ) : m_charArray( new char[ other.m_sizeOfArray ] ), m_sizeOfArray( other.m_sizeOfArray )
{
std::cout << "[Test::copy c'tor] Instance at 0x" << std::hex << this << " copy-constructed from instance 0x" << &other << std::dec << ".\n";
for ( std::size_t i = 0; i < m_sizeOfArray; ++i )
{
m_charArray[ i ] = other.m_charArray[ i ];
}
}
Test( Test&& other ) : m_charArray( other.m_charArray ), m_sizeOfArray( other.m_sizeOfArray )
{
std::cout << "[Test::move c'tor] Instance at 0x" << std::hex << this << " move-constructed from instance 0x" << &other << std::dec << ".\n";
// Steal resources from other instance.
other.m_charArray = nullptr;
other.m_sizeOfArray = 0;
}
~Test()
{
std::cout << "[Test::d'tor] Instance at 0x" << std::hex << this << " is being discarded.\n";
delete [] m_charArray;
}
Test& operator = ( const Test& rightHandSide )
{
std::cout << "[Test::copy assignment operator] Instance at 0x" << std::hex << this << " is being copy-assigned from instance 0x" << &rightHandSide << std::dec << ".\n";
// prevent self-assignment
if ( this == &rightHandSide )
{
return *this;
}
delete [] m_charArray;
m_charArray = nullptr;
m_sizeOfArray = rightHandSide.m_sizeOfArray;
if ( rightHandSide.m_sizeOfArray == 0 )
{
// Other instance is empty. Nothing to copy.
return *this;
}
m_charArray = new char[ rightHandSide.m_sizeOfArray ];
for ( std::size_t i = 0; i < m_sizeOfArray; ++i )
{
m_charArray[ i ] = rightHandSide.m_charArray[ i ];
}
return *this;
}
Test& operator = ( Test&& rightHandSide )
{
std::cout << "[Test::move assignment operator] Instance at 0x" << std::hex << this << " is being move-assigned from instance 0x" << &rightHandSide << std::dec << ".\n";
// prevent self-assignment
if ( this == &rightHandSide )
{
return *this;
}
// Steal resources from other instance and give it ours (it will shortly be destroyed anyway).
std::swap( m_charArray, rightHandSide.m_charArray );
std::swap( m_sizeOfArray, rightHandSide.m_sizeOfArray );
return *this;
}
private:
char* m_charArray;
std::size_t m_sizeOfArray;
};
int main()
{
Test a( new char[ 56 ], 56 );
a = Test( new char[ 200 ], 200 );
}