COMP2004
Programming Practice
2002 Summer School


Kevin Pulo
School of Information Technologies
University of Sydney


(page 1)


Unix development tools




(page 2)


make


OBJS = main.o student.o course.o
CXXFLAGS = -Wall -g
LDFLAGS = -lm

all: prog
prog: $(OBJS)
$(CXX) $(CXXFLAGS) $(LDFLAGS) \
-o prog $(OBJS)
clean:
rm -f $(OBJS)


(page 3)


gdb


Segmentation fault (core dumped)


(page 4)


Simple shell




(page 5)


Shell / environment variables




(page 6)


If



if cmp file1.txt file2.txt; then
echo "files same"
elif diff -i file1.txt file2.txt; then
echo "files same except case"
else
echo "files different"
fi


(page 7)


Alternate if




(page 8)


stdout -> shell variable


echo "f1.h f2.h f3.h" > file.lst
filelist=`cat file.lst`
cat $filelist
cat `cat file.lst`
cat $(cat file.lst)


(page 9)


while


count=1
while [ $count -le 10 ]; do
echo "$count"
count=$(($count + 1))
done


while :; do
if [ -e "file.txt" ]; then
break
fi
sleep 1
done


(page 10)


Command line parameters


#!/gnu/usr/bin/bash
while [ $# -ge 2 ]; do
echo "$1" "$2"
shift
done


bash$ sample a bc defgh a bc
bc defgh


(page 11)


case


case "$1" in
-d*)
cmd="diff"
;;
-c*)
cmd="cmp"
;;
*)
exit 1
;;
esac
$cmd file1.txt file2.txt


(page 12)


for and pipes


#!/gnu/usr/bin/bash
for infile in tests/*.in; do
name=`basename $infile .in`
if prog < $infile | cmp - \
tests/$name.out; then
echo "$name : passed"
else
echo "$name : failed"
fi
done


(page 13)


Useful Unix utilities





(page 14)


Course survey




(page 15)


Advanced C++




(page 16)


Template Functions


template
typename vector::size_type
find(const vector &v,
const T &value) {
for (typename vector::size_type
i = 0; i < v.size(); ++i)
if (v[i] == value) return i;
return v.size();
}
vector vi;
find(vi, 42);


(page 17)


Template Classes


template
class Node {
T value;
Node *next;
...
};
  • Heavy reliance on operators
  • All template code in .h files
    • Only time this is allowed


(page 18)


Exceptions






(page 19)


Exceptions


struct Error { int i;
Error(int i) : i(i) {} };
struct OtherError { };


try {
throw Error(42);
} catch (Error e) {
cout << e.i << endl;
throw OtherError();
} catch (...) {
throw;
}


(page 20)


Exception Safety




(page 21)


Exception Unsafe Code


void some_function(string name) {
Person *fred = new Person();

fred->setName(name);

delete fred;
}


(page 22)


Fixing with try/catch


void some_function(string name) {
Person *fred = new Person(name);
try {
fred->setName(name);
} catch (...) {
delete fred;
throw;
}
delete fred;
}


(page 23)


Fixing with auto_ptr


void some_function(string name) {
Person *fredp = new Person(name);
auto_ptr fred(fredp);

fred->setName(name);
}


(page 24)


String streams




(page 25)


New style


int main() {
string s = "42 15";
istringstream is(s);
int i, j;
is >> i >> j;

ostringstream os;
os << i << "." << j;
s = os.str();
cout << s << endl;
}


(page 26)