Skip to content

Commit dd6bd97

Browse files
authored
Update 002_grammar_aligned_storage.cpp
1 parent f5c6c67 commit dd6bd97

File tree

1 file changed

+48
-1
lines changed

1 file changed

+48
-1
lines changed
Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,48 @@
1-
1
1+
#include <iostream>
2+
#include <type_traits>
3+
#include <string>
4+
5+
template<class T, std::size_t N>
6+
class static_vector
7+
{
8+
// properly aligned uninitialized storage for N T's
9+
typename std::aligned_storage<sizeof(T), alignof(T)>::type data[N];
10+
std::size_t m_size = 0;
11+
12+
public:
13+
// Create an object in aligned storage
14+
template<typename ...Args> void emplace_back(Args&&... args)
15+
{
16+
if( m_size >= N ) // possible error handling
17+
throw std::bad_alloc{};
18+
19+
// construct value in memory of aligned storage
20+
// using inplace operator new
21+
new(&data[m_size]) T(std::forward<Args>(args)...);
22+
++m_size;
23+
}
24+
25+
// Access an object in aligned storage
26+
const T& operator[](std::size_t pos) const
27+
{
28+
// note: needs std::launder as of C++17
29+
return *reinterpret_cast<const T*>(&data[pos]);
30+
}
31+
32+
// Delete objects from aligned storage
33+
~static_vector()
34+
{
35+
for(std::size_t pos = 0; pos < m_size; ++pos) {
36+
// note: needs std::launder as of C++17
37+
reinterpret_cast<T*>(&data[pos])->~T();
38+
}
39+
}
40+
};
41+
42+
int main()
43+
{
44+
static_vector<std::string, 10> v1;
45+
v1.emplace_back(5, '*');
46+
v1.emplace_back(10, '*');
47+
std::cout << v1[0] << '\n' << v1[1] << '\n';
48+
}

0 commit comments

Comments
 (0)