1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
#include <iostream>
#include <memory>
#include <initializer_list>
#include <algorithm>
#include <iterator>
struct my_array
{
my_array() = default ;
explicit my_array( std::size_t n ) : sz(n), ptr( new int[n]{} ) {}
// http://en.cppreference.com/w/cpp/utility/initializer_list
// http://en.cppreference.com/w/cpp/algorithm/copy
my_array( std::initializer_list<int> ilist ) : my_array( ilist.size() ) // for testing
{ std::copy( ilist.begin(), ilist.end(), ptr ) ; }
my_array( const my_array& that ) : my_array( that.sz )
{ std::copy_n( that.ptr, sz, ptr ) ; } // http://en.cppreference.com/w/cpp/algorithm/copy_n
my_array( my_array&& that ) noexcept { swap(that) ; }
// copy-and-swap assignment operator (aka unifying assignment operator)
// see: Canonical implementations: assignment operators
// http://en.cppreference.com/w/cpp/language/operators
my_array& operator= ( my_array that ) noexcept { swap(that) ; return *this ; }
~my_array() { delete[] ptr ; }
void swap( my_array& that ) noexcept // http://en.cppreference.com/w/cpp/algorithm/swap
{ using std::swap ; swap(sz,that.sz) ; swap(ptr,that.ptr) ; }
my_array& operator+= ( const my_array& that )
{
if( that.sz )
{
my_array temp( sz + that.sz ) ;
std::copy_n( ptr, sz, temp.ptr ) ;
std::copy_n( that.ptr, that.sz, temp.ptr+sz ) ;
swap(temp) ;
}
return *this ;
}
private:
std::size_t sz = 0 ;
int* ptr = nullptr ; // raw owning ptr:
// see: Canonical implementations: Binary arithmetic operators
// http://en.cppreference.com/w/cpp/language/operators
friend my_array operator+ ( my_array first, const my_array& second )
{ return first += second ; }
// see: Canonical implementations: Stream extraction and insertion
// http://en.cppreference.com/w/cpp/language/operators
friend std::ostream& operator<< ( std::ostream& stm, const my_array& arr )
{
stm << "[ " ;
std::copy( arr.ptr, arr.ptr+arr.sz, std::ostream_iterator<int>( stm, " " ) ) ;
return stm << ']' ;
}
};
void swap( my_array& a, my_array& b ) noexcept { a.swap(b) ; }
int main()
{
const my_array a { 10, 11, 12, 13, 14, 15 } ;
const my_array b { 56, 57, 58, 59, 60, 61, 62, 63, 64 } ;
std::cout << a << " + " << b << " == " << a+b << '\n' ;
const my_array c = a+b ;
std::cout << c << '\n' ;
my_array d ;
std::cout << b << " + " << a << " == " << b+a << '\n' ;
d = b + a ;
std::cout << d << '\n' ;
}
|