FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Change `deferred_init` to use `aligned_storage`, closes #9 · feiyunwill/cppfront@72f84b5 · GitHub

Commit 72f84b5

Browse files
committed
Change deferred_init to use aligned_storage, closes hsutter#9
Also fixes `auto&&
1 parent 4eb0839 commit 72f84b5

1 file changed

Lines changed: 8 additions & 9 deletions

File tree

‎include/cpp2util.h‎

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -373,21 +373,20 @@ using in =
373373
template<typename T>
374374
class deferred_init {
375375
bool init = false;
376-
union {
377-
int i;
378-
T t;
379-
};
376+
std::aligned_storage<sizeof(T), alignof(T)> data;
377+
378+
auto t() -> T& { return *std::launder(reinterpret_cast<T*>(&data)); }
380379

381380
template<typename U>
382381
friend class out;
383382

384383
public:
385-
deferred_init() noexcept : i {0} { }
386-
~deferred_init() noexcept { if (init) t.~T(); }
387-
auto value() noexcept -> T& { Default.expects(init); return t; }
384+
deferred_init() noexcept { }
385+
~deferred_init() noexcept { if (init) t().~T(); }
386+
auto value() noexcept -> T& { Default.expects(init); return t(); }
388387

389-
auto construct (auto ...args) -> void { Default.expects(!init); new (&t) T(std::forward<decltype(args)>(args)...); init = true; }
390-
auto construct_list(auto ...args) -> void { Default.expects(!init); new (&t) T{std::forward<decltype(args)>(args)...}; init = true; }
388+
auto construct (auto&& ...args) -> void { Default.expects(!init); new (&data) T(std::forward<decltype(args)>(args)...); init = true; }
389+
auto construct_list(auto&& ...args) -> void { Default.expects(!init); new (&data) T{std::forward<decltype(args)>(args)...}; init = true; }
391390
};
392391

393392
template<typename T>

0 commit comments

Comments
 (0)

Back | FazBrowse Home | New Git URL