// --------------
// HeapArrays.c++
// --------------
#include <algorithm> // copy, count, fill
#include <cassert> // assert
#include <cstddef> // ptrdiff_t, size_t
#include <iostream> // cout, endl
#include <vector> // vector
const std::size_t s = 10;
const int v = 2;
void f (int p[]) {
assert(sizeof(p) == 4);
++p;
++p[0];
++*p;}
void g (int* p) {
assert(sizeof(p) == 4);
++p;
++p[0];
++*p;}
int main () {
using namespace std;
cout << "HeapArrays.c++" << endl;
{
int* const a = new int[s];
fill(a, a + s, v);
assert(count(a, a + s, v) == s); // warning: comparison between signed and unsigned integer expressions
f(a);
assert(a[1] == v + 2);
g(a);
assert(a[1] == v + 4);
delete [] a;
}
{
int* const a = new int[s];
fill(a, a + s, v);
int* const b = a;
assert(&a[1] == &b[1]);
int* const x = new int[s];
copy(a, a + s, x);
assert( a[1] == x[1]);
assert(&a[1] != &x[1]);
delete [] a;
delete [] x;
}
{
int* const a = new int[s];
fill(a, a + s, v);
int* b = new int[s];
fill(b, b + s, v);
// b = a; // memory leak
copy(a, a + s, b);
assert( a[1] == b[1]);
assert(&a[1] != &b[1]);
delete [] a;
delete [] b;
}
{
// int* const a = new double[10]; // error: cannot convert 'double*' to 'int* const' in initialization
// double* const a = new int[10]; // error: cannot convert 'int*' to 'double* const' in initialization
}
{
vector<int> x(s, v);
assert(x.size() == s);
assert(x[0] == v);
vector<int> y(x);
assert(x.size() == y.size());
assert( x[1] == y[1]);
assert(&x[1] != &y[1]);
vector<int> z(2 * s, v);
x = z;
assert(x.size() == z.size());
assert( x[1] == z[1]);
assert(&x[1] != &z[1]);
}
cout << "Done." << endl;
return 0;}
syntax highlighted by Code2HTML, v. 0.9.1