Coverage Report

Created: 2025-09-17 06:57

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/brpc/src/butil/shared_object.h
Line
Count
Source
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
19
#ifndef BUTIL_SHARED_OBJECT_H
20
#define BUTIL_SHARED_OBJECT_H
21
22
#include "butil/intrusive_ptr.hpp"                   // butil::intrusive_ptr
23
#include "butil/atomicops.h"
24
25
26
namespace butil {
27
28
// Inherit this class to be intrusively shared. Comparing to shared_ptr,
29
// intrusive_ptr saves one malloc (for shared_count) and gets better cache
30
// locality when the ref/deref are frequent, in the cost of lack of weak_ptr
31
// and worse interface.
32
class SharedObject {
33
friend void intrusive_ptr_add_ref(SharedObject*);
34
friend void intrusive_ptr_release(SharedObject*);
35
36
public:
37
0
    SharedObject() : _nref(0) { }
38
0
    int ref_count() const { return _nref.load(butil::memory_order_relaxed); }
39
    
40
    // Add ref and returns the ref_count seen before added.
41
    // The effect is basically same as butil::intrusive_ptr<T>(obj).detach()
42
    // except that the latter one does not return the seen ref_count which is
43
    // useful in some scenarios.
44
    int AddRefManually()
45
0
    { return _nref.fetch_add(1, butil::memory_order_relaxed); }
46
47
    // Remove one ref, if the ref_count hit zero, delete this object.
48
    // Same as butil::intrusive_ptr<T>(obj, false).reset(NULL)
49
0
    void RemoveRefManually() {
50
0
        if (_nref.fetch_sub(1, butil::memory_order_release) == 1) {
51
0
            butil::atomic_thread_fence(butil::memory_order_acquire);
52
0
            delete this;
53
0
        }
54
0
    }
55
56
protected:
57
0
    virtual ~SharedObject() { }
58
private:
59
    butil::atomic<int> _nref;
60
};
61
62
0
inline void intrusive_ptr_add_ref(SharedObject* obj) {
63
0
    obj->AddRefManually();
64
0
}
65
66
0
inline void intrusive_ptr_release(SharedObject* obj) {
67
0
    obj->RemoveRefManually();
68
0
}
69
70
} // namespace butil
71
72
73
#endif // BUTIL_SHARED_OBJECT_H