We’ll write our smart unique pointer class to understand the std::unique_ptr class very well. We have no other intended purpose. Let’s enjoy that and practice our core C++ skills.
We base our functions on the std::unique_ptr class to select our member functions.
In this way, the functions below are enough to create a basic custom unique pointer class. If more is needed, it can be added whether the intended function exists at the std::unique_ptr class or not.
Additionally, our class provides these features:
- Has to be generic using a template
- Has to disable copy constructor and assignment
- Has to provide their functions for const objects except for the transfer and reset functions.
Okay, all codes will be coded with C++17 standards.
Here is the basic unique smart pointer class:
If we have a look at the class:
We encapsulated the type of T * pointer named ptr as a private member. That provides ownership.
The two constructors: one of them does not take the pointer and initializes the pointer as a nullptr. The other takes a pointer and initializes the pointer with the parameter.
Copy semantic functions are deleted to avoid copying.
Move semantic functions are defined. Move constructor provides transferring the resource from the unique pointer object u to *this. Then, it stores the null pointer in the object, u.
Move assignment operator function transfers resource from u to *this. This may perform when the unique pointer class exists. That’s why we have to clean the *this’s resource before the transferring.
The destructor deletes the resource if it’s not a null pointer.
Operator-> and operator* provide access to resources owned by *this
The function, named “get” provides access to a resource
The function, named “reset” replaces the managed resource. It takes the new resource pointer as a parameter and its default value is a null pointer that can be invoked without a parameter.
Operator bool function checks if the object owns a resource or not.
The function, named “swap” swaps the resources of *this and other. std::swap function may be used inside the function.
Question: The private member T*ptr is accessible by the move constructor and move assignment functions are also the function of swap. This can access the private data of each other. How can it be possible?
Answer: The access modifiers like the private, work on a class level, not on an object level. These objects, this and others can access each other private data.
Here is the main function where we tested our class inside.
u1 resource is existed
Hi! from myEmbeddedWorld!
In the next article, we’ll dive into the standard library’s shared pointer.