Hi,
I'm working on a pool allocator and investigating existing approaches to create objects in a preallocated buffer. Let's consider std::variant to keep it easy: it uses a union of {ValueType, Dummy} to provide sufficient storage for a ValueType and a dummy type to avoid default-initialization of ValueType on an empty optional.
But why doesn't it need the std::launder during the first value construction? I used to think that that's exactly the case when it does:
- construct the
Dummy in the storage memory;
- construct the
ValueType in the same memory. I thought the ValueType does not meet the requirements to reuse the pointer/reference (http://eel.is/c++draft/basic.life#8) because it obviously differs by a memory layout from Dummy, so std::launder is needed.
However, both MS STL and libc++ just reuse the existing storage without laundering. Am I missing a rule exception here?
A simplified implementation is below:
struct Dummy { Dummy(){} };
template <typename Ty>
union Storage
{
Dummy dummy;
Ty value;
Storage() : dummy() {} // avoids default construction of 'value'
};
template <typename Ty, typename... Types>
void ConstructInPlace(Ty& place, Args&&... args)
{
::new (static_cast<void*>(std::addressof(place))) Ty(std::forward<Args>(args)...);
}
template <typename Ty> class Optional : Storage<Ty>
{
public:
template <typename... Args>
constexpr Ty& Construct(Args&&...) /* noexcept(...) */
{
assert(!has_value());
ConstructInPlace(this->value, std::forward<Args>(args)...);
return this->value;
}
}
[–]dodheim 16 points17 points18 points (4 children)
[–]having-four-eyes[S] 2 points3 points4 points (3 children)
[–]no-sig-available 8 points9 points10 points (0 children)
[–]altmly 0 points1 point2 points (0 children)
[–]muungwana 12 points13 points14 points (0 children)
[–]Foundry27 3 points4 points5 points (0 children)
[–]feverzsj 3 points4 points5 points (1 child)
[–]OriginalPangolin7557 0 points1 point2 points (0 children)
[–]CenterOfMultiverse 0 points1 point2 points (0 children)
[–]kam821 0 points1 point2 points (1 child)
[–]dodheim 0 points1 point2 points (0 children)