Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

undefined behavior from reinterpret_cast #54

Open
changkhothuychung opened this issue Dec 24, 2024 · 2 comments
Open

undefined behavior from reinterpret_cast #54

changkhothuychung opened this issue Dec 24, 2024 · 2 comments

Comments

@changkhothuychung
Copy link

https://github.com/bemanproject/inplace_vector/blob/main/include/beman/inplace_vector/inplace_vector.hpp#L364-L367
Suppose T is a user-defined type, wouldn't this reinterpret_cast result in an undefined behavior? A solution would be to use std::launder.

template <class __T, size_t __N> struct __aligned_storage2 {
  alignas(__T) byte __d[sizeof(__T) * __N];
  constexpr __T *__data(size_t __i) noexcept {
    __IV_EXPECT(__i < __N);
    return reinterpret_cast<__T *>(__d) + __i;
  }
  constexpr const __T *__data(size_t __i) const noexcept {
    __IV_EXPECT(__i < __N);
    return reinterpret_cast<const __T *>(__d) + __i;
  }
};
@wusatosi
Copy link
Member

Sorry I am not familiar with std::launder, Can you elaborate on why this would result in undefined behavior?

@jbab
Copy link
Collaborator

jbab commented Jan 14, 2025

There is no undefined behaviour here, https://en.cppreference.com/w/cpp/language/reinterpret_cast#Explanation, paragraph 5.
Basically we put Ts in and get Ts out. Also, the proper alignment is ensured.

Of course, it takes more than the quoted code to prove the point. The implementation of inplace_vector has to make sure that we really only put Ts in. This is easy to review, though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants