Skip to content

Scoped_Ptr

DryPerspective edited this page Sep 23, 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.

This header provides a class lite_ptr for the situation where EBO is absent and it is important that the size of a smart pointer matches that of its raw pointer. This is similar to a scoped_ptr but only supports non-function, stateless deleters. These deleters should be default-constructible and copyable. Other than that, its interface is identical to that of scoped_ptr, save for the fact that get_deleter returns an entirely new instance of a deleter rather than the specific instance tied to the pointer.

scoped_ptr offers support for std::auto_ptr. If for whatever reason you are using this library on C++17 and up, it can be disabled through use of the DP_CPP17 macro.

This header is included in cpp98/memory.h

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