Mistake on this page?
Report an issue in GitHub or email us

Shared Pointer

A shared pointer is a "smart" pointer that retains ownership of an object by using reference counting across all smart pointers referencing that object.

It is similar to the std::shared_ptr class introduced in C++11. However, this is not a compatible implementation, as there are no weak pointers, no make_shared, no custom deleters, and so on.

Usage: SharedPtr<Class> ptr(new Class())

When ptr is passed around by a value, the copy constructor and destructor manage the reference count of the raw pointer. If the counter reaches zero, delete is called on the raw pointer.

SharedPtr class reference

Public Member Functions
constexpr SharedPtr ()
 Create empty SharedPtr not pointing to anything. More...
constexpr SharedPtr (std::nullptr_t)
 Create empty SharedPtr not pointing to anything. More...
 SharedPtr (T *ptr)
 Create new SharedPtr. More...
 ~SharedPtr ()
 Destructor. More...
 SharedPtr (const SharedPtr &source)
 Copy constructor. More...
 SharedPtr (SharedPtr &&source)
 Move constructor. More...
SharedPtr operator= (const SharedPtr &source)
 Copy assignment operator. More...
SharedPtr operator= (SharedPtr &&source)
 Move assignment operator. More...
void reset (T *ptr)
 Replaces the managed pointer with a new unmanaged pointer. More...
void reset ()
 Replace the managed pointer with a null pointer. More...
T * get () const
 Raw pointer accessor. More...
uint32_t use_count () const
 Reference count accessor. More...
T & operator* () const
 Dereference object operator. More...
T * operator-> () const
 Dereference object member operator. More...
 operator bool () const
 Boolean conversion operator. More...

Shared pointer example

/*
 * Copyright (c) 2006-2020 Arm Limited and affiliates.
 * SPDX-License-Identifier: Apache-2.0
 */
#include "platform/SharedPtr.h"

int main(void)
{
    struct MyStruct {
        int a;
    };

    // Create shared pointer
    SharedPtr<MyStruct> ptr(new MyStruct);

    // Increase reference count
    SharedPtr<MyStruct> ptr2(ptr);

    ptr = nullptr; // Reference to the struct instance is still held by ptr2

    ptr2 = nullptr; // The raw pointer is freed
}

Important Information for this Arm website

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies. If you are not happy with the use of these cookies, please review our Cookie Policy to learn how they can be disabled. By disabling cookies, some features of the site will not work.