Skip to content

Commit

Permalink
Replace all remaining instances of reinterpret_cast with std::bit_cast
Browse files Browse the repository at this point in the history
  • Loading branch information
liuzicheng1987 committed Dec 4, 2024
1 parent b98f0e5 commit 470fce8
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 11 deletions.
13 changes: 5 additions & 8 deletions include/rfl/Result.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

#include <algorithm>
#include <array>
#include <bit>
#include <iostream>
#include <optional>
#include <stdexcept>
Expand Down Expand Up @@ -314,20 +315,16 @@ class Result {
}
}

T& get_t() noexcept {
return *std::launder((reinterpret_cast<T*>(t_or_err_.data())));
}
T& get_t() noexcept { return *std::bit_cast<T*>(t_or_err_.data()); }

const T& get_t() const noexcept {
return *std::launder((reinterpret_cast<const T*>(t_or_err_.data())));
return *std::bit_cast<const T*>(t_or_err_.data());
}

Error& get_err() noexcept {
return *std::launder((reinterpret_cast<Error*>(t_or_err_.data())));
}
Error& get_err() noexcept { return *std::bit_cast<Error*>(t_or_err_.data()); }

const Error& get_err() const noexcept {
return *std::launder((reinterpret_cast<const Error*>(t_or_err_.data())));
return *std::bit_cast<const Error*>(t_or_err_.data());
}

void move_from_other(Result<T>& _other) noexcept {
Expand Down
7 changes: 4 additions & 3 deletions include/rfl/Variant.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#define RFL_VARIANT_HPP_

#include <array>
#include <bit>
#include <cstdint>
#include <limits>
#include <optional>
Expand Down Expand Up @@ -80,7 +81,7 @@ class Variant {
auto t = T{std::forward<Args>(_args)...};
destroy_if_necessary();
move_from_type(std::move(t));
return *std::launder(reinterpret_cast<T*>(data_.data()));
return *std::bit_cast<T*>(data_.data());
}

/// Emplaces a new element into the variant.
Expand Down Expand Up @@ -384,13 +385,13 @@ class Variant {
template <IndexType _i>
auto& get_alternative() noexcept {
using CurrentType = internal::nth_element_t<_i, AlternativeTypes...>;
return *std::launder(reinterpret_cast<CurrentType*>(data_.data()));
return *std::bit_cast<CurrentType*>(data_.data());
}

template <IndexType _i>
const auto& get_alternative() const noexcept {
using CurrentType = internal::nth_element_t<_i, AlternativeTypes...>;
return *std::launder(reinterpret_cast<const CurrentType*>(data_.data()));
return *std::bit_cast<const CurrentType*>(data_.data());
}

void move_from_other(Variant<AlternativeTypes...>&& _other) noexcept {
Expand Down

0 comments on commit 470fce8

Please sign in to comment.