Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / native_client_sdk / src / libraries / sdk_util / ref_object.h
blob707a335e17669c9ea02a3cadcc9ef4c2acd5d5d3
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef LIBRARIES_SDK_UTIL_REF_OBJECT
6 #define LIBRARIES_SDK_UTIL_REF_OBJECT
8 #include <stdlib.h>
9 #include "pthread.h"
11 #include "sdk_util/atomicops.h"
13 namespace sdk_util {
15 class ScopedRefBase;
18 * RefObject
20 * A reference counted object. RefObjects should only be handled by ScopedRef
21 * objects.
23 * When the object is first created, it has a reference count of zero. It's
24 * first incremented when it gets assigned to a ScopedRef. When the last
25 * ScopedRef is reset or destroyed the object will get released.
28 class RefObject {
29 public:
30 RefObject() {
31 ref_count_ = 0;
35 * RefCount
37 * RefCount returns an instantaneous snapshot of the RefCount, which may
38 * change immediately after it is fetched. This is only stable when all
39 * pointers to the object are scoped pointers (ScopedRef), and the value
40 * is one implying the current thread is the only one, with visibility to
41 * the object.
43 int RefCount() const { return ref_count_; }
45 protected:
46 virtual ~RefObject() {}
48 // Override to clean up object when last reference is released.
49 virtual void Destroy() {}
51 void Acquire() {
52 AtomicAddFetch(&ref_count_, 1);
55 bool Release() {
56 Atomic32 val = AtomicAddFetch(&ref_count_, -1);
57 if (val == 0) {
58 Destroy();
59 delete this;
60 return false;
62 return true;
65 private:
66 Atomic32 ref_count_;
68 friend class ScopedRefBase;
71 } // namespace sdk_util
73 #endif // LIBRARIES_SDK_UTIL_REF_OBJECT