August 21st, 2025
0 reactions

Thoughts on creating a tracking pointer class, part 9: Conversion

Last time, we added the ability to create tracking pointers from const objects. But we discovered that you could not convert a tracking_ptr<T> to a tracking_ptr<const T>. But this should be possible, because the available operations on a tracking pointer to a const object is a subset of the operations available to a tracking pointer to a non-const object.

We can perform the conversion by copying/moving the underlying tracking_ptr_base.

template<typename T>
struct tracking_ptr : tracking_ptr_base<std::remove_cv_t<T>>
{
private:                                                
    using base = tracking_ptr_base<std::remove_cv_t<T>>;

public:
    T* get() const { return this->tracked; }

    using base::base;                                     
    tracking_ptr(base const& other) : base(other) {}      
    tracking_ptr(base&& other) : base(std::move(other)) {}
};

If somebody has a tracking_ptr<T> it converts to a tracking_ptr<const T> by means of our two new constructors, which copy/move the common tracking_ptr_base<T>, which is the thing that babysits the shared_ptr<T*>. To avoid repetitive typing, we make base an alias for the base class tracking_ptr_base<std::remove_cv_t<T>>.

We don’t need to write custom assignment operators because assignment can be performed by converting the tracking_ptr<T> to a tracking_ptr<const T>, and then assigning the tracking_ptr<const T>.

But wait, there’s a problem with this. We’ll look at it next time.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments