Say I have a class My<X>
with a member X x
that it won't modify without being moved/destroyed. I believe that x
should be a const X
, because the variable shouldn't be mutable throughout the lifespan of My<X>
, no matter how its value was given or how it will be gotten. That said, I want the value and its type to be preserved through My
, as if perfectly forwarded instead.
(I've penciled in pass-through conversion operators just to show the signatures explicitly. In practice, there may be no operators at all, but methods/functions will still use x
as if by conversion with these CV/references.)
template<class X> struct My {
const X x;
/* 1. */ operator X && (void) && noexcept;
//{ return std::forward<X>(std::move(*this).x); }
/* 2. */ operator const X && (void) && noexcept;
//{ return std::forward<const X>(std::move(*this).x); }
/* 3. */ operator X const& (void) const& noexcept
{ return x; }
};
I included #2 but I think I can rule it out. I've looked up const X &&
enough to remember that it has few interpretations and few use cases. The const
here was added, I only want to preserve const
if it already was.
As for #1, the call to std::forward<X>
should be a static_cast<X &&>
, so I believe the type is right. Can I use perfect forwarding this way, or will I have copies or dangling references or something?
(I recently did a lot of tests on CV-qualifications and references, sanity checks really, and discovered some weird behaviors that left me a lot less sure of myself. One is that adding const
to an lvalue reference has no effect. In fact, it produces a warning, unlike with std::add_const_t
. That may actually be a factor here.)
Can a moving struct perfectly forward a member currently marked const
? Is there a reason I shouldn't?