Computer Science 3 Lab Exercises C++
This repo documents the transition of the third CS3 lab exercises from Java to C++. The Course is about programming concepts rather than a specific language.
Changes
Worksheet 1
Element:
- In Element every mention of Element is replaced with
std::shared_ptr<Element>
. - Command cmd becomes
std::shared_ptr<Command>
. - In the constructor
Element(Command cmd)
usesstd::make_shared<Command>(cmd)
to produce astd::shared_ptr
. - The destructor
~Element()
may be configured to log destruction of removed Elements.
CommandList:
- the
Element root
now is ashared_ptr<Element>
and is initialized inline withstd::make_shared<Element>(Command("root"))
. This is necessary because a shared pointer is empty upon construction. - All member functions previously returning
Command
s now returnstd::make_shared<Command>
. This is to allow for returningnullptr
if something went wrong. -
getElement()
now returnsstd::shared_ptr<Element>
. -
getPos()
now returnsstd::make_shared<Command>
. - Where appropriate the funtion parameter
int
has been replaced withunsigned int
to prohibit passing negative values. - In
add(Command cmd)
std::make_shared<Element>(cmd)
is used to create a newElement
. Here is easily visible how std::make_shared() is the C++ equivalent to Javas
new` operator. - The
std::bad_alloc
-Exception possibly thrown bystd::make_shared<Element>()
is not catched inadd()
, to not introducetry{} catch{}
too early. Thus add() wont returnnullptr
, but crash the program if an error occures.
Trivia
smart pointers
- smart pointers point to NULL on construction.
- They can easily be checked for content with
if (mySmartPointer)
//has content
else
//is empty
- A unique pointer will be destroyed at the end of it's scope.
- A smart pointer will be destroyed when all of it's references are overwritten or the scope of the last reference ends.