Smart pointers (background info)
Smart pointers are designed to make dynamic memory more accessible and safe to use. They (i.e., smart pointers) are implemented as wrappers around raw pointers, providing behaviors reminiscent of the raw pointers you’re so familiar with, while safeguarding against the pitfalls and opportunities for errors that you’ve probably experienced. We will provide a more complete introduction to smart pointers later in this semester.
Unique pointer (background info)
For today's assignment, we will provide a focused introduction to the unique pointer. The mantra of the unique pointer is exclusive ownership and accordingly implements a move-only type. The unique pointer implementation utilizes the resource acquisition is initialization (RAII) programming idiom, where the lifetime of a dynamically allocated object (i.e. the resource) is tied to the unique pointer object that owns it.
The allocation of the dynamically allocated object (i.e. resource acquisition) owned by the unique pointer happens during a construction (initialization). Deallocation of that object is always completed during destruction. A non-null unique pointer, by virtue of its name, always owns what it points to. Therefore, two objects of this type will never share the same resource. This invariant is maintained by disabling the copy mechanisms for this type.
In this activity
You will write a simplified implementation of a unique pointer, which we will call UniquePtr. Objects derived from this blueprint will maintain a unique pointer to a dynamically allocated object of type T.
Function Signatures and Behaviors
UniquePtr(const T& data);
Constructs a UniquePtr, initializing holder_ with a new dynamically allocated object of type T initialized with value data.
UniquePtr(const UniquePtr& lhs);
Deleted.
~UniquePtr();
Deallocates the dynamically allocated object pointed to by holder_.
UniquePtr& operator=(const UniquePtr& lhs);
Deleted.
T& operator*();
Returns a reference to the object pointed to by holder_.
UML Class Diagram
class UniquePtr
- holder_ : T*
+ UniquePtr(data : const T&)
+ UniquePtr(lhs: const UniquePtr&)
+ ~UniquePtr( )
+ operator=(lhs: const UniquePtr&) : UniquePtr&
+ operator*( ) : T&