-
Notifications
You must be signed in to change notification settings - Fork 0
/
person.cpp
95 lines (78 loc) · 2.01 KB
/
person.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include "person.h"
#include <vector>
#include <iostream>
#include <memory>
#include <assert.h>
#include <array>
// To prevent the compiler of optimizing it
extern "C" void do_something_special(const uint8_t*, std::size_t);
// Non-copyable but moveable, because of the unique_ptr
template<>
struct VersionedPerson<PersonVersionNumber>::PersonImpl final
{
int16_t _age;
std::shared_ptr<std::string> _u;
std::array<uint8_t, 2048> aBigMember;
const char* name() const
{
do_something_special(aBigMember.data(), aBigMember.size());
return _u->c_str();
}
int age() const
{
do_something_special(aBigMember.data(), aBigMember.size());
return _age;
}
PersonImpl(const PersonImpl&) = default;
PersonImpl& operator=(PersonImpl&) = default;
PersonImpl(PersonImpl&&) = default;
PersonImpl(const std::string& name, int age):
_age(age),
_u(std::shared_ptr<std::string>(new std::string(name)))
{
}
~PersonImpl()
{
do_something_special(aBigMember.data(), aBigMember.size());
std::cout << "Deleted PersonImpl\n";
}
};
template<>
VersionedPerson<PersonVersionNumber>::VersionedPerson(const VersionedPerson& other):
impl(cafetine::Alloc<Impl>::copy(other.impl))
{
std::cout << "Copied person\n";
}
template<>
VersionedPerson<PersonVersionNumber>::VersionedPerson(const char* name, int age)
{
std::cout << "Created person\n";
assert(!impl);
cafetine::Alloc<Impl>::alloc(impl, name, age);
assert(impl);
impl.reset();
assert(!impl);
cafetine::Alloc<Impl>::alloc(impl, name, age);
assert(impl);
}
template<>
VersionedPerson<PersonVersionNumber>::VersionedPerson(VersionedPerson&& other):
impl(cafetine::Alloc<Impl>::move(other.impl))
{
std::cout << "Moved person\n";
}
template<>
VersionedPerson<PersonVersionNumber>::~VersionedPerson()
{
std::cout << "Destroyed person\n";
}
template<>
const char* VersionedPerson<PersonVersionNumber>::name() const
{
return impl->name();
}
template<>
int VersionedPerson<PersonVersionNumber>::age() const
{
return impl->age();
}