All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
anyUniquePtr.h
1//
2// Copyright 2019 Pixar
3//
4// Licensed under the terms set forth in the LICENSE.txt file available at
5// https://openusd.org/license.
6//
7#ifndef PXR_BASE_TF_ANY_UNIQUE_PTR_H
8#define PXR_BASE_TF_ANY_UNIQUE_PTR_H
9
10#include "pxr/pxr.h"
11#include "pxr/base/tf/api.h"
12
13#include <type_traits>
14
15PXR_NAMESPACE_OPEN_SCOPE
16
27{
28public:
29 template <typename T>
30 static TfAnyUniquePtr New() {
31 static_assert(!std::is_array<T>::value, "Array types not supported");
32 return TfAnyUniquePtr(new T());
33 }
34
35 template <typename T>
36 static TfAnyUniquePtr New(T const &v) {
37 static_assert(!std::is_array<T>::value, "Array types not supported");
38 return TfAnyUniquePtr(new T(v));
39 }
40
42 : _ptr(other._ptr)
43 , _delete(other._delete)
44 {
45 other._ptr = nullptr;
46 // We don't set other._delete to nullptr here on purpose. Invoking
47 // delete on a null pointer is not an error so if we can ensure that
48 // _delete is never null we can call it unconditionally.
49 }
50
51 TfAnyUniquePtr& operator=(TfAnyUniquePtr &&other) {
52 if (this != &other) {
53 _delete(_ptr);
54 _ptr = other._ptr;
55 _delete = other._delete;
56 other._ptr = nullptr;
57 }
58 return *this;
59 }
60
61 TfAnyUniquePtr(TfAnyUniquePtr const&) = delete;
62 TfAnyUniquePtr& operator=(TfAnyUniquePtr const&) = delete;
63
65 _delete(_ptr);
66 }
67
69 void const *Get() const {
70 return _ptr;
71 }
72
73private:
74 template <typename T>
75 explicit TfAnyUniquePtr(T const *ptr)
76 : _ptr(ptr)
77 , _delete(&_Delete<T>)
78 {}
79
80 template <typename T>
81 static void _Delete(void const *ptr) {
82 delete static_cast<T const *>(ptr);
83 }
84
85private:
86 void const *_ptr;
87 void (*_delete)(void const *);
88};
89
90PXR_NAMESPACE_CLOSE_SCOPE
91
92#endif
A simple type-erased container that provides only destruction, moves and immutable,...
Definition: anyUniquePtr.h:27
void const * Get() const
Return a pointer to the owned object.
Definition: anyUniquePtr.h:69