summaryrefslogtreecommitdiffstats
path: root/mojo/public/bindings/lib/shared_ptr.h
blob: 537b39e6cfc287d8edbfaf97e33433307c798518 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef MOJO_PUBLIC_BINDINGS_LIB_SHARED_PTR_H_
#define MOJO_PUBLIC_BINDINGS_LIB_SHARED_PTR_H_

#include "mojo/public/bindings/lib/shared_data.h"

namespace mojo {
namespace internal {

// Used to manage a heap-allocated instance of P that can be shared via
// reference counting. When the last reference is dropped, the instance is
// deleted.
template <typename P>
class SharedPtr {
 public:
  SharedPtr() {}

  explicit SharedPtr(P* ptr) {
    impl_.mutable_value()->ptr = ptr;
  }

  // Default copy-constructor and assignment operator are OK.

  P* get() {
    return impl_.value().ptr;
  }
  const P* get() const {
    return impl_.value().ptr;
  }

  P* operator->() { return get(); }
  const P* operator->() const { return get(); }

 private:
  class Impl {
   public:
    ~Impl() {
      if (ptr)
        delete ptr;
    }

    Impl() : ptr(NULL) {
    }

    Impl(P* ptr) : ptr(ptr) {
    }

    P* ptr;

   private:
    MOJO_DISALLOW_COPY_AND_ASSIGN(Impl);
  };

  SharedData<Impl> impl_;
};

}  // namespace mojo
}  // namespace internal

#endif  // MOJO_PUBLIC_BINDINGS_LIB_SHARED_PTR_H_