File: shared_ref.hpp

package info (click to toggle)
libfplus 0.2.13-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,904 kB
  • sloc: cpp: 27,543; javascript: 634; sh: 105; python: 103; makefile: 6
file content (53 lines) | stat: -rw-r--r-- 1,625 bytes parent folder | download | duplicates (3)
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
// Copyright 2015, Tobias Hermann and the FunctionalPlus contributors.
// https://github.com/Dobiasd/FunctionalPlus
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

#pragma once

#include <memory>

namespace fplus
{

// A std::shared_ptr expresses
// optionality of the contained value (can be nullptr)
// and shared ownership that can be transferred.
// A std::optional expresses optionality only.
// The standard does not provide a class to
// express only shared ownership without optionality.
// shared_ref fills this gap.
// It is recommended to use make_shared_ref for constructing an instance.
template <typename T>
class shared_ref
{
public:
    shared_ref(const shared_ref&) = default;
    shared_ref(shared_ref&&) = default;
    shared_ref& operator=(const shared_ref&) = default;
    shared_ref& operator=(shared_ref&&) = default;
    ~shared_ref() = default;

    T* operator->() { return m_ptr.get(); }
    const T* operator->() const { return m_ptr.get(); }

    T& operator*() { return *m_ptr.get(); }
    const T& operator*() const { return *m_ptr.get(); }

    template <typename XT, typename...XTypes>
    friend shared_ref<XT> make_shared_ref(XTypes&&...args);

private:
    std::shared_ptr<T> m_ptr;
    shared_ref(T* value) :m_ptr(value) { assert(value != nullptr);  }
};

// http://stackoverflow.com/a/41976419/1866775
template <typename T, typename...Types>
shared_ref<T> make_shared_ref(Types&&...args)
{
    return shared_ref<T>(new T(std::forward<Types>(args)...));
}

} // namespace fplus