Construct an empty object without the default constructor

女生的网名这么多〃 提交于 2020-01-22 16:25:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!