在没有默认构造函数的情况下构造一个空对象 [英] Construct an empty object without the default constructor

查看:67
本文介绍了在没有默认构造函数的情况下构造一个空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 F 类型.我知道 F 为空,但是 F 没有默认构造函数,所以我不能使用 F()来构造它.无论如何,有没有一种方法可以获取类型为 F 的有效对象?我似乎还记得有人提到过,有一种奥秘地使用工会的方法.理想情况下,它将是 constexpr 友好的.

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.

这很有用,因为无捕获的lambda仅在C ++ 20中获得了默认构造函数.在C ++ 17中,如果我想将lambda传递给模板"并在没有该lambda实例的情况下调用该lambda,则需要能够从该类型中重构它.

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);

推荐答案

对于您自己的类型,您可以从自身复制或移动构造对象: F f = f .这本身并不会导致UB,请参见 CWG363 .但是,对于编译器提供的闭包类型,即使您知道它为空,也不清楚.

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.

这篇关于在没有默认构造函数的情况下构造一个空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆