Lab #3

Dynamic memory, namespaces and friend functions for pvector

Cristiano De Michele

Today

  1. Introduction to C++ (part III) — a class that allocates its memory at run time, with new and delete (example N6), and namespaces (example N7).
  2. Lab #2: the solution — the constructor with initializer_list and the operators you wrote last time.
  3. Task: new methods for pvector — operator() to use a vector as a C array, “scalar times vector” through a friend function, rint(), element-wise products mulcw() and divcw(), and << to print a vector with std::cout.

Along the way: returning a reference to an element, overloading on const, and functions that are not methods but can read the private members of a class.

Part 1
Introduction to C++ (part III)

Where we left off

  • An operator is a method of its left operand: A + B is A.operator+(B); A is *this inside the method, B the argument.
  • const methods only read *this; vector arguments go by const pvector&; the assignment operators return *this by reference, the others a new object.
  • 2.0*A does not compile: double is not a class and has no methods. Today it comes with a friend function.

Today, first:

  • the size of the array of pvector is fixed when we compile (NT). What if it is known only when the program runs (e.g. the number of particles read from a file)? Example N6: dynamic memory;
  • the same name in two different libraries: namespaces (example N7).

Fixed size vs dynamic memory

Fixed size (pvector)

ntype v[NT];  // NT known when compiling
  • the array is inside the object: it is created and destroyed together with it;
  • nothing to give back: the destructor is empty.

Dynamic (N6)

int *v;              // only an address
v = new int[len];    // len known at run time
...
delete[] v;          // give the memory back
  • As in C: int *v is a pointer, the address of the first element; v[i] reads the i-th element exactly as for an array.
  • new int[len] asks for memory for len integers and returns its address: the C++ version of C’s malloc(len*sizeof(int)). delete[] v gives it back, like free(v) ([] because it was taken for an array). nullptr: the C++ NULL.
  • Memory taken with new is not freed automatically: someone must call delete[]. In a class, that someone is the destructor.

Example N6: mydynvec.hpp

examples/N6_a_dynamic_class/mydynvec.hpp

#include<cstdlib>
#include<iostream>
#include<stdio.h>
class myvec
{
  // private members
  int *v; // pointer to array
  int len; // allocated int
public:
  // constructor
  myvec()
    {
      len=0;
      v=nullptr;
    }
  // destructor
  ~myvec()
    {
      if (v!=nullptr)
        delete[] v;
    }

  // allocate memory for array
  void alloc(int l) 
    {
      len=l;
      v = new int[len];// new double[]
    }
  // assign value to (i+1)-th element of the array
  void set(int i, int val)
    {
      v[i] = val;
    }
  // get (i+1)-th element of array
  // a=V(i);
  // V(i) = 2.0;
  int get(int i) const // (*this) is passed implicitly, with the const modifier
    {
      return v[i];
    }
  // get actual length of array
  int length(void) const
    {
      return len;
    }
  // resize array (enlarge)
  void resize(int l)
    {
      int *vt;
      vt = new int[l];
      // initialize with all elements and 0 if larger
      for (int i=0; i < l; i++)
        vt[i] = (i < len)?v[i]:0.0;
      len = l;
      if (v!=nullptr)
        delete [] v;
      v=vt;
    }
 };

Example N6: how myvec works

  • Constructor: no memory yet. len=0, and v=nullptr records that nothing has been allocated (the destructor checks it).
  • alloc(l): stores the length in len and takes memory for len integers with new int[len]. The values are not initialized: main sets them with set().
  • Destructor: finally it has a job. When the object dies it gives the memory back with delete[] v, only if something was allocated (v!=nullptr).
  • resize(l) cannot “enlarge” the memory it already has. It allocates a new array vt of l elements, copies the old elements and puts 0 in the new ones ((i < len)?v[i]:0.0, the conditional operator of C), frees the old array with delete [] v and keeps in v the address of the new one.
  • get() and length() are const, as in N1: they only read the object, which is passed implicitly as *this (the comment on line 37).
  • The class does not check the index: set(20, 1) on an array of 10 elements writes outside it, with no error message (undefined behaviour, as in C).

Example N6: mydynvec.cpp

examples/N6_a_dynamic_class/mydynvec.cpp

#include "./mydynvec.hpp"
int main(int argc, char** argv)
{
  // class instantiation
  myvec v;

  // allocate memory
  v.alloc(10);

  // initialize array elements
  for (int i=0; i < 10; i++)
    {
      v.set(i, 0);
    }
  // print out value of third element
  std::cout << "v[2]=" << v.get(2) << std::endl;

  // resize the vector
  v.resize(11);

  // set 11-th element  
  v.set(10, -2);

  // print out third element and 11-th one
  std::cout << "v[2]=" << v.get(2) << " v[10]=" << v.get(10) << std::endl;
}
g++ -std=c++17 -Wall -o mydynvec mydynvec.cpp
./mydynvec
v[2]=0
v[2]=0 v[10]=-2
  • The size of the array (10 with alloc(10), then 11 with resize(11)) is decided while the program runs: it could come from a file. With ntype v[NT] it must be known when compiling. After resize(11) the old elements are still there (v[2]=0).
  • There is no delete[] in main: when v goes out of scope, at the end of main, its destructor frees the memory.

Dynamic memory: what can go wrong

Add at the end of main of N6:

myvec w = v;   // w is created as a copy of v
free(): double free detected in tcache 2
Aborted
  • The copy made by the compiler copies the members one by one: w.v gets the address stored in v.v, not a copy of the array. At the end of main both destructors call delete[] on the same memory: the program prints its output, then crashes when w and v are destroyed. The same happens with myvec w; w = v;: the operator= generated by the compiler copies the address too.
  • A class that allocates memory must also say how to copy itself (copy constructor and operator= that copy the array): we will not need it, which is one reason why our pvector keeps a fixed-size array.
  • Calling alloc() twice loses the first array (memory leak): nobody can free it any more. Compile with -fsanitize=address to find these errors: ERROR: LeakSanitizer: detected memory leaks.

Example N7: namespace.cpp

examples/N7_namespace/namespace.cpp

#include<iostream>
int c; // global variable
namespace nsA
{
  int a; // nsA::a
  int b; // nsA::b
}
namespace nsB
{
  int a; // nsB::a
  int b; // nsB::b
}
namespace nsC
{
  int a; // nsC::a
  int b; // nsC::b
}

// using namespace nsC;
// using namespace std;

int main(int argc, char**argv)
{
  nsA::a = 1;
  nsB::a = 2;
  nsC::a = 3; // default namespace is nsC (see using namespace nsC above)
  std::cout << "nsA::a=" << nsA::a << "\n";
  std::cout << "nsB::a=" << nsB::a << "\n";
  std::cout << "nsC::a=" << nsC::a << "\n";

  return 0;
}
g++ -std=c++17 -Wall -o namespace \
    namespace.cpp && ./namespace
nsA::a=1
nsB::a=2
nsC::a=3

Namespaces

  • A namespace gives a family name to variables, functions and classes: nsA::a, nsB::a and nsC::a are three different variables. Two libraries can both have an a (or a vector) without clashing.
  • :: is the scope operator, as in vecder::show() of N5. std::cout: cout lives in std, the namespace of the standard library. c (line 2) is declared outside any namespace: it is in the global namespace, and can be written c or ::c.
  • Without prefix the compiler does not look inside the namespaces: a = 1; gives error: 'a' was not declared in this scope.
  • using namespace nsC; (line 19, now a comment) makes the names of nsC visible without prefix: uncomment it and a = 3; is nsC::a = 3; (the comment on line 26).
  • With using namespace nsA; too, a is in two namespaces: error: reference to 'a' is ambiguous.
  • using namespace std; (line 20) lets you write cout. Handy in a .cpp, to be avoided in a header: it would act on every file that includes it.

Part 2
Lab #2: the solution

Constructor with initializer_list

project/pvector.hpp

  // curly brace initialization, i.e.
  // pvector V={1.0,2.0,3.0};
  pvector(std::initializer_list<ntype> L)  // overloading constructor
    {
      int c=0;
      for (ntype el: L) // loop over all element in the list L
                        // hence "el" will be, in turn, each element of L
        {
          if (c < NT)
            {
              v[c] = el;
            }
          c++;
        }
      for ( ;c < NT; c++) // if L has fewer than NT elements, set the others to 0
        {
          v[c]=0.0;
        }
      //std::cout << "curly brace constructor\n";
    }
  • c counts the elements of L read so far; only the first NT are copied into v (if (c < NT)), the others are ignored: a longer list never writes outside the array.
  • The second for has no initialization: it starts from the current c and sets to 0 the components the list did not give: pvector C = {4.0}; is (4,0,0).

+= and -=

project/pvector.hpp

  // add vector and assign
  pvector& operator+=(const pvector& V2)
    {
      for (int i=0; i < NT; i++)
        {
          v[i] += V2.v[i];
        }
      return (*this);
    }
  // subtract vector and assign
  pvector& operator-=(const pvector& V2)
    {
      for (int i=0; i < NT; i++)
        {
          v[i] -= V2.v[i];
        }
      return (*this);
    }
  • No local vector: v[i] += V2.v[i] changes in place the components of *this, the left operand.
  • The method is not const, because it changes *this, and it returns *this by reference, as operator=: (D += B) *= 2.0 then acts on D twice.

Scalar product and norm()

project/pvector.hpp

  // scalar product (vector times vector)
  ntype operator*(const pvector& V2) const
    {
      ntype sp=0;
      for (int i=0; i < NT; i++)
        sp += v[i]*V2.v[i];
      return sp;
    }
  // norm of vector
  ntype norm(void) const
    {
      return sqrt((*this)*(*this));
    }
  • sp (scalar product) is a local ntype: it must start from 0, then it accumulates v[i]*V2.v[i]. The result is a number, returned by value.
  • norm() uses the operator: (*this)*(*this) is (*this).operator*(*this), the scalar product of the object with itself.

Vector times and divided by a scalar

project/pvector.hpp

  // vector times scalar 
  // A*s <=> A.operator*(s)
  pvector operator*(ntype s) const
    {
      pvector VT;
      for (int i=0; i < NT; i++)
        // note that inside the class is possible to use private member of objects
        // belonging to the class (such as member v of VT in this case)
        VT.v[i] = v[i]*s;
      return VT;
    }

  // vector divided by scalar 
  pvector operator/(ntype s) const
    {
      pvector VT;
      for (int i=0; i < NT; i++)
        // note that inside the class is possible to use private member of objects
        // belonging to the class (such as member v of VT in this case)
        VT.v[i] = v[i]/s;
      return VT;
    }
  • A local VT is filled with v[i]*s (or v[i]/s) and returned by value: A*s and A/s change neither A nor s.
  • The for has no braces: its body is the single statement VT.v[i] = ...; the two comment lines in between do not count.

*= and /=

project/pvector.hpp

  // multiply by scalar and assign result to vector
  pvector& operator*=(ntype s)
    {
      for (int i=0; i < NT; i++)
        v[i] *= s;
      return (*this);
    }
  // divide by scalar and assign result to vector
  pvector& operator /=(ntype s)
    {
      for (int i=0; i < NT; i++)
        v[i] /= s;
      return (*this);
    }
  • Same pattern as +=: the components of *this change in place, and *this is returned by reference. The argument is a number, passed by value.
  • operator /= (with a space, line 9) is the same as operator/=: spaces between operator and the symbol do not matter.

== and the cross product ^

project/pvector.hpp

  // compare two vectors
  bool operator==(const pvector& V2) const
    {
      for (int i=0; i < NT; i++)
        {
          if (v[i] != V2.v[i])
            return 0;
        }
      return 1;
    }
  // cross product: only for 3D vectors
  pvector operator^(const pvector& V2) const
    {
      if (NT==3)
        {
          pvector VT;
          VT.v[0] = v[1]*V2.v[2]-v[2]*V2.v[1];
          VT.v[1] = v[2]*V2.v[0]-v[0]*V2.v[2];
          VT.v[2] = v[0]*V2.v[1]-v[1]*V2.v[0];
          return VT;
        }
      else
        {
          std::cout << "Cross product not defined\n";
          exit(1);
        }
    }
  • operator== compares the components one by one and returns as soon as two differ. The int values 0 and 1 are converted to the return type bool, i.e. false and true (writing return false; and return true; would be clearer).
  • operator^ computes the cross product only if NT==3; for any other dimension it prints a message and stops the program with exit(1) (from <cstdlib>).

Part 3
New tasks for pvector

The task

Download again project_classes.zip (course page; unzip it elsewhere, not over your own file): the new project/pvector.hpp contains the methods of Lab #2, implemented (Part 2), and the skeleton of today’s methods, at the end of the class. The TODO list:

// [X] overloading of operator == (check whether two vectors are equal)
// [X] overloading of ^ operator for cross product 
// [*] overloading of (...) operator () to use vector as C arrays, e.g. v(0)=1
// [*] "scalar times vector" through friend function
// [*] rint(), i.e. if V is a vector rint(V) is the vector with components rounded to nearest integer
// [*] mulcw, multiplication element wise: C=mulcw(A,B), i.e. C(i) = A(i)*B(i)
// [*] divcw, division element wise: C=divcw(A,B), i.e. C(i) = A(i)/B(i)
// [*] overloading of << for output (friend function)
//
// Discuss random number generator class with Mersenne-Twister
// [ ] random(L), random vector inside a box of length L
// [ ] random_orient() random unit on unit sphere (marsaglia) 

Until you fill the bodies, the skeleton compiles with 7 warnings no return statement in function returning non-void (one for each new method that must return a value). The goal of the lab: make project/pvector.cpp, also in the zip, compile without warnings and print the output shown at the end. Random numbers (the last two lines of the list) come next time.

operator(): the skeleton

project/pvector.hpp

  // This is needed to access elements of const vector objects
  // this is like having following arguments: operator()(const pvector *this, int i) 
  // where (implicit, i.e. (*this) ) first argument is the "calling" object
  // V(i) = 1.0;
  // cout << V(0);
  // V         (   i          )
  // operand       operand
  ntype operator()(int idx) const
    {

    }

  // this is like having following arguments: operator()(pvector *this, int i) 
  // where first (implicit, i.e. (*this) ) argument is the "calling" object
  // pvector A;
  // double val;
  // std::cout << A(1);
  // A(1)=val;
  ntype& operator()(int idx)
    {

    }
  • A(1) is the method call A.operator()(1): the parentheses are an operator too, the call operator, with A on the left and 1 as argument. Each version needs one line, return v[idx];. They replace get() and set() with an array-like notation: A(1) reads the component, A(1) = 5.0 writes it.

Two versions: overloading on const

ntype& operator()(int idx)        // returns the element itself
ntype  operator()(int idx) const  // returns a copy of its value
  • The two versions have the same parameter list and differ only by the const after it, i.e. by the const of *this: this overloading is allowed. On a const pvector (or through a const pvector&) only the const version can be called; on a non-const vector the compiler calls the other one, which allows writing.
  • The const version must not allow writing, so it returns a value (a const ntype& would also work).
  • Without the const version, K(2) on const pvector K gives error: no match for call to '(const pvector) (int)'; inside mulcw() and divcw() below, whose arguments are const pvector&, the same error with (int&).

Returning a reference to an element

A(1) = 5.0;      // A.operator()(1) = 5.0;   the non-const version, returning ntype&
  • A(1) = 5.0; needs on the left the component v[1] of A, not a copy of its value: hence ntype&, a reference to v[1]. The reference is valid after the call because v[1] lives as long as A (a reference to a local variable, instead, would point to a dead object: Lab #1).
  • With ntype (by value) also in the non-const version, A(1) = 5.0; gives error: lvalue required as left operand of assignment: the call returns a copy of the value, a temporary number with no place in memory (not an lvalue), and assigning to it makes no sense, like 3 = 5.0;.

Scalar times vector: a friend function

project/pvector.hpp

  // scalar times vector 
  // (*this) is not implicitly passed to operator* in this case, 
  // being a friend operator of pvector class
  // pvector A;
  // double s;
  // s*A
  friend pvector operator*(ntype s, const pvector& V2)
    {

    }
  • 2.0*A cannot be a method: its left operand is a double. It must be a function operator*(2.0, A), with both operands as arguments: no *this.
  • friend inside the class: the function is not a method, but it can read the private members of pvector (V2.v[i]), as a method would.
  • Without friend it would be a method with three operands (*this, s, V2): error: 'pvector pvector::operator*(ntype, const pvector&)' must have either zero or one argument.
  • The body is that of A*s (Part 2): a local VT with VT.v[i] = s*V2.v[i], returned by value. 2.0*A and A*2.0 then give the same vector.

rint()

project/pvector.hpp

  // rint() function
  // pvector A, B={1.1,2.2,3.3};
  // A = rint(B);
  friend pvector rint(const pvector& V2)
    {

    }
  • Another friend function. It is not a method, so the vector is an argument: rint(B), not B.rint(). It returns a new vector, by value.
  • It rounds each component with the rint() of <cmath>, the one for numbers: VT.v[i] = rint(V2.v[i]); (the argument V2.v[i] is a number, not a pvector).
  • Next slides: how rint() rounds, and why we need it.

mulcw() and divcw()

project/pvector.hpp

  // mulcw: component wise multiplication, i.e. C=mulcw(A,B), i.e. C(i) = A(i)*B(i)
  friend pvector mulcw(const pvector& V1, const pvector& V2)
    {

    }

  // divcw: component wise division, i.e. C=divcw(A,B), i.e. C(i) = A(i)/B(i)
  friend pvector divcw(const pvector& V1, const pvector& V2)
    {

    }
  • Two more friend functions, called with both vectors as arguments: mulcw(A,B).
  • mulcw and divcw multiply (divide) component by component, C(i) = A(i)*B(i), and can use the new operator(): VT(i) = V1(i)*V2(i);. VT(i) on the left needs the non-const version (it writes); V1(i) and V2(i) the const one, because V1 and V2 are const pvector&.

rint() and round()

rint(x) rounds x to the nearest integer. When x is exactly halfway (2.5) it goes to the even integer (the default rounding mode of the processor); round() instead always goes away from zero:

rint(2.5)=2   rint(3.5)=4   rint(-2.5)=-2      round(2.5)=3   round(-2.5)=-3
  • The program must not depend on how the halves are rounded: in our use (next slide) the two choices are equally good.

Why rint(): minimum image convention

In a cubic box of side L with periodic boundary conditions, a particle interacts with the closest periodic image of the other one. For each component, rint(dr/L) is the number of box sides by which dr must be shifted:

double L=10.0;
pvector dr={6.0,-7.5,1.0};    // r_i - r_j
dr = dr - L*rint(dr/L);       // (-4,2.5,1)
  • x: 6.0/10 = 0.6, rint gives 1, 6.0-10 = -4; y: -0.75 gives -1, -7.5+10 = 2.5; z: 0.1 gives 0, unchanged. Each component ends up in [-L/2, L/2].
  • With our operators the formula is written as on paper, one line for all the components: dr/L (vector divided by scalar), rint() and L*... (friends), -. Without them it would be a loop over the components.
  • At exactly L/2 the two images are equally far: there either rounding is correct.

operator<<: printing with std::cout

project/pvector.hpp

  // pvector V;
  // (std::cout  <<  V ) << "\n";
  //     os      ,     vec
  friend std::ostream& operator<<(std::ostream& os, const pvector& vec)
    {

    }
  • std::cout << V is operator<<(std::cout, V): the left operand is a std::ostream, a class of the standard library we cannot change. So again a friend function.
  • Write into os, not into std::cout: os is the stream on the left of <<. Here it is std::cout, but it can be a file (the configurations of a simulation, later).
  • The output is that of show(), without the final "\n": who writes std::cout << V decides what comes next.
  • Return os itself, by reference: this is what lets you chain several << (next slide).

Chaining <<

std::cout << "v1=" << v1 << " v2=" << v2 << std::endl;
// is evaluated as
((((std::cout << "v1=") << v1) << " v2=") << v2) << std::endl;
// output: v1=(1,2,3) v2=(0.5,-1,2)
  • << groups from left to right (left associativity): the leftmost << is done first, and its result is the left operand of the next one.
  • So every << must return the stream itself, std::cout: return os;, type std::ostream&. The << of the standard library do the same: ours fits in the chain.
  • By reference: a stream cannot be copied. With std::ostream (by value): error: use of deleted function 'std::basic_ostream<...>::basic_ostream(const std::basic_ostream<...>&)'.
  • With void, the chain breaks at the next <<: error: invalid operands of types 'void' and 'const char [2]' to binary 'operator<<'.
  • Compare with =, which groups from right to left: A = B = C is A = (B = C) (Lab #2). Both return a reference, used by the next operator.

The goal: pvector.cpp

project/pvector.cpp: it tests today’s methods. The goal of the lab is to make it compile without warnings and print the output of the next slide.

#include "./pvector.hpp"
int main(void)
{
  pvector A = {1.0, 2.0, 3.0}, B = {0.5, -1.0, 2.0}, C;
  const pvector K = {1.1, -2.5, 3.5};

  std::cout << "A(1)=" << A(1) << "\n";   // operator(): read
  A(1) = 5.0;                             // operator(): write
  std::cout << "A=" << A << "\n";         // operator<<
  std::cout << "K(2)=" << K(2) << "\n";   // const operator()

  C = 2.0*A;         std::cout << "2.0*A=" << C << "\n";
  C = rint(K);       std::cout << "rint(K)=" << C << "\n";
  C = mulcw(A, B);   std::cout << "mulcw(A,B)=" << C << "\n";
  C = divcw(A, B);   std::cout << "divcw(A,B)=" << C << "\n";
  std::cout << A << " " << B << "\n";     // chained <<
  return 0;
}

Compile, run, compare

cd ~/csm/project
g++ -std=c++17 -Wall -o pvector pvector.cpp
./pvector
A(1)=2
A=(1,5,3)
K(2)=3.5
2.0*A=(2,10,6)
rint(K)=(1,-2,4)
mulcw(A,B)=(0.5,-5,6)
divcw(A,B)=(2,-5,1.5)
(1,5,3) (0.5,-1,2)
  • rint(K): 1.1 becomes 1; -2.5 and 3.5 are halfway and go to the even integer, -2 and 4.
  • No warnings with -Wall: the 7 warnings of the skeleton disappear when every method returns its value. Then set ntype to float: same output.

Classic pitfalls

  • ntype instead of ntype& in the non-const operator(): A(1) = 5.0; does not compile (lvalue required ...).
  • Only the non-const operator(): it cannot be called on a const object. In mulcw(const pvector& V1, ...) the vector V1 is const, so V1(i) does not compile: no match for call to '(const pvector) (int&)' (no operator() usable on a const pvector).
  • friend forgotten in operator*(ntype s, const pvector& V2): inside the class it becomes a method, which also receives *this. Three operands for a binary *: error: ... must have either zero or one argument (a method gets only the right operand).

Classic pitfalls (continued)

  • operator<< writing into std::cout instead of os: it always prints on the screen, even when the stream on the left is a file. Returning void: std::cout << A << "\n" does not compile (chaining).
  • round() instead of rint(): they differ when a value is exactly halfway (round(-2.5) is -3, rint(-2.5) is -2), so the output of rint(K) would change.
  • No index check in operator(), as in get(): with NT = 3, A(3) reads outside the array, with no error (undefined behaviour).

Checklist for today

Next lab: random numbers (Mersenne Twister), random(L) and random_orient(); generic programming (templates).