问题
Suppose I have a type F
. I know that F
is empty, but F
has no default constructor, so I can't use F()
to construct it. Is there a way to obtain a valid object of type F
anyway? I seem to recall a mention that there was such a way with arcane usage of unions. Ideally, it would be constexpr
friendly.
This can be useful because captureless lambdas only gained a default constructor in C++20. In C++17, if I want to "pass a lambda to a template" and call that lambda without having an instance of it, I need to be able to reconstruct it from the type.
auto const f = [](int x) { return x; };
using F = decltype(f);
static_assert(std::is_empty_v<F>);
static_assert(!std::is_default_constructible_v<F>);
magically-construct-an-F(42);
回答1:
For your own types, you could copy- or move-construct an object from itself: F f = f
. This does not lead to UB by itself, see CWG363.
However, it is not so clear for a compiler-provided closure type, even if you know it is empty.
回答2:
but
F
has no default constructor
If that's the case, then the user either explicitly deleted it or it was implicitly deleted because the user provided some other constructor. In either case, the type is not Trivial.
If an object is non-Trivial, then to create an object of that type without copying/moving from an existing instance, you must explicitly call some sort of constructor. There's no getting around that.
Even the common initial sequence rules of a union don't allow you to create the other object. It only permits access to the non-static data members of the other object. Since your object is empty, this is of no value to you.
来源:https://stackoverflow.com/questions/57007728/construct-an-empty-object-without-the-default-constructor