Skip to content

Scoped_Ptr

DryPerspective edited this page Sep 21, 2023 · 7 revisions

Scoped_Ptr is a C++98 analogue of std::unique_ptr. It it entirely scope-local - it cannot be copied. It also cannot be moved as C++98 has no move semantics. It will successfully clean up the resource it manages upon destruction, however that may be. It can be given a deleter to clean up the resource in a particular way. Both single-value and array versions included. The interface should match std::unique_ptr almost exactly, just without move semantics.

Note that for a stateless, non-function deleter, sizeof(scoped_ptr<T>) == sizeof(T*) will hold only if your compiler uses the empty base optimization. This was a common optimization in C++98, but was only made mandatory for these types in C++11. Without EBO, a scoped_ptr will be slightly larger than its raw pointer counterpart.

Functions

release Releases ownership of the underlying resource, and returns the pointer to it
reset Destroys the managed object and resets the pointer to being empty
swap Swaps the objects managed by two pointers
get Returns the raw pointer to the underlying resource.
get_deleter Returns the stored deleter object for the pointer
operator bool Returns whether the pointer currently manages a resource, or if it is null
operator*
operator->
Single object version only: Access stored resource
operator[] Array version only: Provide indexed access to the managed array
operator==
operator!=
operator<
operator<=
operator>
operator>=
Compares the managed resource with some other value
operator<< Inserts the value of the managed pointer into the provided ostream

Sample Code

#include "cpp98/scoped_ptr.h"

struct PrintAndDelete{
    template<typename T>
    void operator()(T* in){
       Print("DELETING POINTER");  //Custom deleter to print when we delete a pointer
       delete in;
    }
};

int someCStyleInterface(int* in);

int func(){
    dp::scoped_ptr<int, PrintAndDelete> ptr(new int);

    if(foo){
        throw Exception("I don't like foo");  //"DELETING POINTER"
    }

    someCStyleInterface(ptr.get()); //Very easy to call things expecting a raw pointer

    return 0; //"DELETING POINTER"
}

Clone this wiki locally