1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18// Date: Fri Sep 7 12:15:23 CST 2018
19
20#ifndef BUTIL_PTR_CONTAINER_H
21#define BUTIL_PTR_CONTAINER_H
22
23namespace butil {
24
25// Manage lifetime of a pointer. The key difference between PtrContainer and
26// unique_ptr is that PtrContainer can be copied and the pointer inside is
27// deeply copied or constructed on-demand.
28template <typename T>
29class PtrContainer {
30public:
31 PtrContainer() : _ptr(NULL) {}
32
33 explicit PtrContainer(T* obj) : _ptr(obj) {}
34
35 ~PtrContainer() {
36 delete _ptr;
37 }
38
39 PtrContainer(const PtrContainer& rhs)
40 : _ptr(rhs._ptr ? new T(*rhs._ptr) : NULL) {}
41
42 void operator=(const PtrContainer& rhs) {
43 if (rhs._ptr) {
44 if (_ptr) {
45 *_ptr = *rhs._ptr;
46 } else {
47 _ptr = new T(*rhs._ptr);
48 }
49 } else {
50 delete _ptr;
51 _ptr = NULL;
52 }
53 }
54
55 T* get() const { return _ptr; }
56
57 void reset(T* ptr) {
58 delete _ptr;
59 _ptr = ptr;
60 }
61
62 operator void*() const { return _ptr; }
63
64private:
65 T* _ptr;
66};
67
68} // namespace butil
69
70#endif // BUTIL_PTR_CONTAINER_H
71