-
Notifications
You must be signed in to change notification settings - Fork 1
/
pimpl_ptr.h
45 lines (33 loc) · 1.42 KB
/
pimpl_ptr.h
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
#ifndef MEMORY_PIMPL_PTR_H
#define MEMORY_PIMPL_PTR_H
#include <cassert>
#include <memory>
namespace utils {
template<class T>
class PimplPtr {
public:
using ElementType = typename std::unique_ptr<T>::element_type;
PimplPtr(): p_(std::make_unique<T>()) {
static_assert(sizeof(T) > 0, "Probably, you forgot to declare constructor explicitly");
}
explicit PimplPtr(std::unique_ptr<T>&& p) noexcept: p_(std::move(p)) { assert(p_ != nullptr); }
PimplPtr(PimplPtr&&) noexcept = default;
PimplPtr& operator =(PimplPtr&&) noexcept = default;
PimplPtr(const PimplPtr&) noexcept = delete;
PimplPtr& operator =(const PimplPtr&) noexcept = delete;
~PimplPtr() {
static_assert(sizeof(T) > 0, "Probably, you forgot to declare destructor explicitly");
}
const ElementType* get() const noexcept { return p_.get(); }
const ElementType* operator->() const noexcept { return get(); }
const ElementType& operator*() const noexcept { return *get(); }
explicit operator const ElementType*() const noexcept { return get(); }
ElementType* get() noexcept { return p_.get(); }
ElementType* operator->() noexcept { return get(); }
ElementType& operator*() noexcept { return *get(); }
explicit operator ElementType*() noexcept { return get(); }
private:
std::unique_ptr<T> p_; ///> Should be non-const for move semantic
};
} // namespace utils
#endif // MEMORY_PIMPL_PTR_H