-
Notifications
You must be signed in to change notification settings - Fork 0
The Shared Pointer
In this page you'll be able to read about the shared pointer exercise
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;
};
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"
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;
If one wants to be able to check whether the shared pointer contains a usable pointer the following code must work:
But on the other hand these statements below should not work!
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.
Made by: Frederik Both Rokkjær, Frederik Kronvang Gade and Christian Olsen