Dynamic memory, namespaces and friend functions for pvector
new and delete (example N6), and namespaces (example N7).initializer_list and the operators you wrote last time.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.
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:
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;Fixed size (pvector)
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.new is not freed automatically: someone must call delete[]. In a class, that someone is the destructor.mydynvec.hppexamples/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;
}
};myvec workslen=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().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).set(20, 1) on an array of 10 elements writes outside it, with no error message (undefined behaviour, as in C).mydynvec.cppexamples/N6_a_dynamic_class/mydynvec.cpp
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).delete[] in main: when v goes out of scope, at the end of main, its destructor frees the memory.Add at the end of main of N6:
free(): double free detected in tcache 2
Aborted
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.operator= that copy the array): we will not need it, which is one reason why our pvector keeps a fixed-size array.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.namespace.cppexamples/N7_namespace/namespace.cpp
// 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;
}nsA::a=1
nsB::a=2
nsC::a=3
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.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).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.initializer_listproject/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.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
v[i] += V2.v[i] changes in place the components of *this, the left operand.const, because it changes *this, and it returns *this by reference, as operator=: (D += B) *= 2.0 then acts on D twice.norm()project/pvector.hpp
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.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;
}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.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
+=: 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
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>).pvectorDownload 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 skeletonproject/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.constconst 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.const version must not allow writing, so it returns a value (a const ntype& would also work).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&).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).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;.project/pvector.hpp
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.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.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(B), not B.rint(). It returns a new vector, by value.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).rint() rounds, and why we need it.mulcw() and divcw()project/pvector.hpp
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
rint(): minimum image conventionIn 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:
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].dr/L (vector divided by scalar), rint() and L*... (friends), -. Without them it would be a loop over the components.L/2 the two images are equally far: there either rounding is correct.operator<<: printing with std::coutproject/pvector.hpp
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.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).show(), without the final "\n": who writes std::cout << V decides what comes next.os itself, by reference: this is what lets you chain several << (next slide).<<<< groups from left to right (left associativity): the leftmost << is done first, and its result is the left operand of the next one.<< 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.std::ostream (by value): error: use of deleted function 'std::basic_ostream<...>::basic_ostream(const std::basic_ostream<...>&)'.void, the chain breaks at the next <<: error: invalid operands of types 'void' and 'const char [2]' to binary 'operator<<'.=, which groups from right to left: A = B = C is A = (B = C) (Lab #2). Both return a reference, used by the next operator.pvector.cppproject/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;
}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.-Wall: the 7 warnings of the skeleton disappear when every method returns its value. Then set ntype to float: same output.ntype instead of ntype& in the non-const operator(): A(1) = 5.0; does not compile (lvalue required ...).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).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.operator(), as in get(): with NT = 3, A(3) reads outside the array, with no error (undefined behaviour).Next lab: random numbers (Mersenne Twister), random(L) and random_orient(); generic programming (templates).