Line data Source code
1 : /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 : /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 : /* This code is made available to you under your choice of the following sets
4 : * of licensing terms:
5 : */
6 : /* This Source Code Form is subject to the terms of the Mozilla Public
7 : * License, v. 2.0. If a copy of the MPL was not distributed with this
8 : * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 : */
10 : /* Copyright 2013 Mozilla Contributors
11 : *
12 : * Licensed under the Apache License, Version 2.0 (the "License");
13 : * you may not use this file except in compliance with the License.
14 : * You may obtain a copy of the License at
15 : *
16 : * http://www.apache.org/licenses/LICENSE-2.0
17 : *
18 : * Unless required by applicable law or agreed to in writing, software
19 : * distributed under the License is distributed on an "AS IS" BASIS,
20 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 : * See the License for the specific language governing permissions and
22 : * limitations under the License.
23 : */
24 :
25 : #ifndef mozilla_pkix_ScopedPtr_h
26 : #define mozilla_pkix_ScopedPtr_h
27 :
28 : namespace mozilla { namespace pkix {
29 :
30 : // A subset polyfill of std::unique_ptr that does not support move construction
31 : // or move assignment. This is used instead of std::unique_ptr because some
32 : // important toolchains still don't provide std::unique_ptr, including in
33 : // particular Android NDK projects with APP_STL=stlport_static or
34 : // ALL_STL=stlport_shared.
35 : template <typename T, void (&Destroyer)(T*)>
36 : class ScopedPtr final
37 : {
38 : public:
39 0 : explicit ScopedPtr(T* value = nullptr) : mValue(value) { }
40 :
41 : ScopedPtr(const ScopedPtr&) = delete;
42 :
43 0 : ~ScopedPtr()
44 : {
45 0 : if (mValue) {
46 0 : Destroyer(mValue);
47 : }
48 0 : }
49 :
50 : void operator=(const ScopedPtr&) = delete;
51 :
52 : T& operator*() const { return *mValue; }
53 : T* operator->() const { return mValue; }
54 :
55 0 : explicit operator bool() const { return mValue; }
56 :
57 0 : T* get() const { return mValue; }
58 :
59 : T* release()
60 : {
61 : T* result = mValue;
62 : mValue = nullptr;
63 : return result;
64 : }
65 :
66 : void reset(T* newValue = nullptr)
67 : {
68 : // The C++ standard requires std::unique_ptr to destroy the old value
69 : // pointed to by mValue, if any, *after* assigning the new value to mValue.
70 : T* oldValue = mValue;
71 : mValue = newValue;
72 : if (oldValue) {
73 : Destroyer(oldValue);
74 : }
75 : }
76 :
77 : private:
78 : T* mValue;
79 : };
80 :
81 : } } // namespace mozilla::pkix
82 :
83 : #endif // mozilla_pkix_ScopedPtr_h
|