aboutsummaryrefslogtreecommitdiffhomepage
path: root/development/c++/fwd-perfect.cc
diff options
context:
space:
mode:
authorjohannst <johannst@users.noreply.github.com>2023-05-29 20:34:16 +0000
committerjohannst <johannst@users.noreply.github.com>2023-05-29 20:34:16 +0000
commiteaad036407c9546be0de27f61745fef4b6856e56 (patch)
treec270e3fbc87f3b7c9fc25ac60f4f8f611962de5e /development/c++/fwd-perfect.cc
parent87c538b89ea68cf0c133a9243097ffac646e6739 (diff)
downloadnotes-eaad036407c9546be0de27f61745fef4b6856e56.tar.gz
notes-eaad036407c9546be0de27f61745fef4b6856e56.zip
deploy: d2013ee5952bbcf88906a832748783e372f3a939
Diffstat (limited to 'development/c++/fwd-perfect.cc')
-rw-r--r--development/c++/fwd-perfect.cc82
1 files changed, 82 insertions, 0 deletions
diff --git a/development/c++/fwd-perfect.cc b/development/c++/fwd-perfect.cc
new file mode 100644
index 0000000..2fafc3e
--- /dev/null
+++ b/development/c++/fwd-perfect.cc
@@ -0,0 +1,82 @@
+// Copyright (C) 2023 johannst
+
+#include <cassert>
+#include <cstdio>
+#include <new>
+#include <type_traits>
+#include <utility>
+
+struct S {};
+
+struct M {
+ M() {
+ std::puts("M()");
+ }
+ M(const M&) {
+ std::puts("M(M&)");
+ }
+ M(M&&) {
+ std::puts("M(M&&)");
+ }
+ M& operator=(const M&) = delete;
+ M& operator=(M&&) = delete;
+
+ M(S&, int) {
+ std::puts("M(S&)");
+ }
+ M(S&&, int) {
+ std::puts("M(S&&)");
+ }
+ ~M() {
+ std::puts("~M()");
+ }
+};
+
+template<typename T>
+struct option {
+ static_assert(!std::is_reference_v<T>);
+
+ constexpr option() = default;
+
+ template<typename... Params>
+ constexpr option(Params&&... params) : m_has_val(true) {
+ // BAD: does not perfectly forward!
+ // eg, if option(S&&) is invoked, this would invoke M(S&).
+ // new (&m_val) T(params...);
+
+ // GOOD: perfectly forwards params to constructor of T.
+ new (m_val) T(std::forward<Params>(params)...);
+ }
+
+ ~option() {
+ reset();
+ }
+
+ constexpr T& value() {
+ assert(m_has_val);
+ return *reinterpret_cast<T*>(m_val);
+ }
+
+ private:
+ constexpr void reset() {
+ if (!m_has_val) {
+ return;
+ }
+ if constexpr (!std::is_trivially_destructible_v<T>) {
+ value().~T();
+ };
+ }
+
+ alignas(T) char m_val[sizeof(T)];
+ bool m_has_val{false};
+};
+
+int main() {
+ std::puts("==> case 1");
+ // invokes M(S&&, int)
+ option<M> opt1(S{}, 123);
+
+ std::puts("==> case 2");
+ // invokes M() + M(M&&)
+ option<M> x /* option(M&&) + M(M&&) */ = M{} /* M() */;
+}