Skip to content

The Shared Pointer

Frederik Rokkjær edited this page Sep 9, 2020 · 12 revisions

In this page you'll be able to read about the shared pointer exercise

Exercise 1: Making a basic shared pointer

In your endevour to create this entity ensure that it at least has the following properties.

  • It implements the counted pointer idiom
  • Copy construction and assignment is implemented and works as one would expect.
  • Need to be able to use it as a pointer like entity - E.g. the smart pointer idiom
  • Use delegating constructors and others where appropriate.

The way we solved this exercise is by writing this code in APK/SharedPtr/include/SharedPtr.hpp

template <typename T> class SharedPtr
{
public:
  SharedPtr(T *t);
  SharedPtr(const SharedPtr &);
  ~SharedPtr();
  SharedPtr &operator=(const SharedPtr &);
  T &        operator*() const;
  T *        operator->() const;
  size_t     count() const;
};

Exercise 2: Conversions

Exercise 2.1 The ’explicit’ constructor

Inspect your SharedPtr<> template class and discuss which of the constructors, if any, should be explicit and why/why not. A code snippet for or against should be included in your answer

In SharedPtr, 2 constructors are available, so the explicit specifier should be used on the contructor with const SharedPtr&. If Explicit wasn't used the compiler wouldn't be able to determin what contructor to use, and could lead to unspecified behaviour

template <typename T> class SharedPtr
{
public:
  SharedPtr(T *t);
  explicit SharedPtr(const SharedPtr &);
};

Use of explicit specifier from answer in thread(visited 07-09-2020): "https://stackoverflow.com/questions/121162/what-does-the-explicit-keyword-mean"

Use of explicit specifier from answer in thread(visited 07-09-2020): "https://stackoverflow.com/questions/121162/what-does-the-explicit-keyword-mean"

Exercise 2.2 Overloading

Exercise 2.2.1 Which overloads do we use?

Which overloads have been implemented and why? Are there any other overloads that might be useful?

The comparison operator (==) is also a necessity, since it can be used in the conversion to bool. The code for that looks like this

bool       operator==(const T &) const;

Exercise 2.2.2 “Implicit” conversion to bool

If one wants to be able to check whether the shared pointer contains a usable pointer the following code must work:

Picture of Listing 2.1 Conversion to bool

But on the other hand these statements below should not work!

Picture of Listing 2.2 Conversion to bool

Determine exactly what is important to utilise from the language in order to achieve what we want but at the same time inhibit misuse.

To remove the option of misuse you have to make the comparison operator explicit, so that it cannot be implicitly converted to an int.