Commit 2a6b310a836b6437891b85d2773a770eef247ee4
1 parent
56b9b36d
push_back internally using emplace_back
Showing
3 changed files
with
5 additions
and
11 deletions
examples11/04-vectortmpl/vector.h
... | ... | @@ -27,7 +27,7 @@ private: |
27 | 27 | void resize_before_push() { |
28 | 28 | if (size >= cap) { |
29 | 29 | if (cap > std::numeric_limits<decltype(size)>::max() / (2 * sizeof(C))) |
30 | - throw bad_alloc(); | |
30 | + throw length_error("Vector too long"); | |
31 | 31 | unsigned int newcap = (cap == 0) ? 1 : 2 * cap; |
32 | 32 | C *newdata; |
33 | 33 | if constexpr (!std::is_trivially_copyable<C>()) { | ... | ... |
examples11/05-foldexpr/vector.h
... | ... | @@ -27,7 +27,7 @@ private: |
27 | 27 | void resize_before_push() { |
28 | 28 | if (size >= cap) { |
29 | 29 | if (cap > std::numeric_limits<decltype(size)>::max() / (2 * sizeof(C))) |
30 | - throw bad_alloc(); | |
30 | + throw std::length_error("Vector too long"); | |
31 | 31 | unsigned int newcap = (cap == 0) ? 1 : 2 * cap; |
32 | 32 | C *newdata; |
33 | 33 | if constexpr (!std::is_trivially_copyable<C>()) { | ... | ... |
examples11/06-template_metaprogramming/vector.h
... | ... | @@ -54,7 +54,7 @@ private: |
54 | 54 | void resize_before_push() { |
55 | 55 | if (size >= cap) { |
56 | 56 | if (cap > std::numeric_limits<decltype(size)>::max() / (2 * sizeof(C))) |
57 | - throw bad_alloc(); | |
57 | + throw length_error("Vector too long"); | |
58 | 58 | reserve_internal((cap == 0) ? 1 : 2 * cap); |
59 | 59 | } |
60 | 60 | } |
... | ... | @@ -147,26 +147,20 @@ public: |
147 | 147 | } |
148 | 148 | |
149 | 149 | private: |
150 | - template <class T> C &push_back_single(T &&s) { | |
151 | - resize_before_push(); | |
152 | - new (data + size) C(std::forward<T>(s)); | |
153 | - return *(data + size++); | |
154 | - } | |
155 | 150 | |
156 | 151 | public: |
157 | 152 | void reserve(unsigned capacity) { |
158 | 153 | if (capacity > std::numeric_limits<decltype(size)>::max() / (2 * sizeof(C))) |
159 | - throw bad_alloc(); | |
154 | + throw length_error("Vector too long"); | |
160 | 155 | unsigned int cap_rounded_up = round_up_to_power_of_2(capacity); |
161 | 156 | reserve_internal(cap_rounded_up); |
162 | 157 | } |
163 | 158 | |
164 | 159 | template <class T> std::tuple<C &> push_back(T &&s) { |
165 | - C &r = push_back_single(std::forward<C>(s)); | |
160 | + C &r = emplace_back(std::forward<C>(s)); | |
166 | 161 | return std::tuple<C &>(r); |
167 | 162 | } |
168 | 163 | |
169 | -public: | |
170 | 164 | template <class T, class... Args> auto push_back(T &&a, Args &&... args) { |
171 | 165 | auto op1 = push_back(std::forward<C>(a)); |
172 | 166 | auto op2 = push_back(args...); | ... | ... |