-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbefore_after.cpp
72 lines (56 loc) · 2 KB
/
before_after.cpp
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
64
65
66
67
68
69
70
71
72
#include <cstddef>
#include <memory_resource.hpp>
#include <string.hpp>
#include <vector.hpp>
// Bar, the class we will make allocator aware.
struct Bar {
int d_i = 0;
std::vector<int> d_v{};
};
// Foo, the allocator aware version of Bar.
struct Foo {
// See 23.10.7.2 for information on when something can use "allocator
// construction". See also "uses_allocator"
using allocator_type = std::pmr::polymorphic_allocator<std::byte>;
Foo(std::pmr::polymorphic_allocator<std::byte> alloc = {}) : d_v(alloc) {}
Foo(int i, std::pmr::polymorphic_allocator<std::byte> alloc = {})
: d_i(i), d_v(alloc) {}
Foo(int i, const std::pmr::vector<int> &v,
std::pmr::polymorphic_allocator<std::byte> alloc = {})
: d_i(i), d_v(v, alloc) {}
Foo(int i, std::pmr::vector<int> &&v,
std::pmr::polymorphic_allocator<std::byte> alloc = {})
: d_i(i), d_v(std::move(v), alloc) {}
// Note that we cannot use the "pass by value and move" shorthand.
Foo(const Foo &other, std::pmr::polymorphic_allocator<std::byte> alloc = {})
: d_i(other.d_i), d_v(other.d_v, alloc) {}
// This is subtle! We need two move constructors and we're using another
// resource's allocator. Move constructors always move the allocator.
// Assignment never does.
Foo(const Foo &&other)
: d_i(other.d_i), d_v(std::move(other.d_v), other.get_allocator()) {}
Foo(const Foo &&other, std::pmr::polymorphic_allocator<std::byte> alloc)
: d_i(other.d_i), d_v(std::move(other.d_v), alloc) {}
Foo &operator=(const Foo &other) {
d_i = other.d_i;
d_v = other.d_v;
return *this;
}
// Note that this is not (nor can it be) noexcept.
Foo &operator=(Foo &&other) {
d_i = other.d_i;
d_v = std::move(other.d_v);
return *this;
}
allocator_type get_allocator() const noexcept { return d_v.get_allocator(); }
int d_i = 0;
std::pmr::vector<int> d_v{};
};
int main() {
Foo foo1{};
Foo foo2{33};
Foo foo3{33, {1, 2, 3}};
Bar bar1{};
Bar bar2{33};
Bar bar3{33, {1, 2, 3}};
}