Skip to content
Snippets Groups Projects
user avatar
tobiglaser authored
56a8f8a1
History
Name Last commit Last update
.vscode
include
src
.gitignore
CMakeLists.txt
README.md

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) uses std::make_shared<Command>(cmd) to produce a std::shared_ptr.
  • The destructor ~Element() may be configured to log destruction of removed Elements.

CommandList:

  • the Element root now is a shared_ptr<Element> and is initialized inline with std::make_shared<Element>(Command("root")). This is necessary because a shared pointer is empty upon construction.
  • All member functions previously returning Commands now return std::make_shared<Command>. This is to allow for returning nullptr if something went wrong.
  • getElement() now returns std::shared_ptr<Element>.
  • getPos() now returns std::make_shared<Command>.
  • Where appropriate the funtion parameter int has been replaced with unsigned int to prohibit passing negative values.
  • In add(Command cmd) std::make_shared<Element>(cmd) is used to create a new Element. Here is easily visible how std::make_shared() is the C++ equivalent to Javas new` operator.
  • The std::bad_alloc-Exception possibly thrown by std::make_shared<Element>() is not catched in add(), to not introduce try{} catch{} too early. Thus add() wont return nullptr, 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.