c++ - 为什么我要对这个对象进行大括号初始化(值初始化)以使其成为 constexpr?
问题描述
我想我有一种情况,如果我不支持/值初始化一个对象,它就不能是 constexpr,但我认为它只发生在某些编译器上,这会在 Visual Studio 的“我的”版本上编译:
template <typename T>
struct MyClass
{
constexpr MyClass() = default;
int member;
};
template <typename T>
constexpr MyClass<T> makeMyClass(T t)
{
MyClass<T> temp;
// {}^^^
// If I keep the constructor and brace-initialise here the error goes away.
temp.member = 3;
// Uninitialized variable 'temp' in 'constexpr' function, why do I have to initialise?
return temp;
}
int main()
{
constexpr auto myclassobj = makeMyClass(6);
//^^^ If I add constexpr before this line AND I don't
//brace-initialise temp then I get the error:
//error: uninitialized variable ‘temp’ in ‘constexpr’ function
}
我在 constexpr 构造函数默认情况下做错了吗?如果我不 { } 大括号初始化,那么它不再是被调用的构造函数了吗?这就是错误吗?如果我不进行大括号初始化,那么它正在调用一个不是 constexpr 的构造函数?
解决方案
基本问题是您的默认构造函数不能是 constexpr ,因为该类包含int
将与默认构造函数保持统一化的 a 。
如果您使用聚合初始化,空大括号表示您对类的成员进行了值初始化,因此该对象已完全初始化,您可以在constexpr
表达式中使用它。
推荐阅读
- mysql - 在 VIEW 中运行总计
- android - Firestore 忽略对象中的空值
- python - Python - 如何更改按钮列表中一个按钮的颜色
- c++ - 当其中一个为负时,如何将两个 16 位值组合成一个 32 位值?
- java - Java流flatMap,将第一级和第二级对象保留在流中
- netsuite - Netsuite 将发票转换为自定义记录计划脚本
- vega - 如何从点击事件中获取规范内的缩放坐标?
- arrays - 有没有办法将 Array Ref as String 转换为 Perl 中的实际 Array ref?- 不能使用 string("ARRAY(...)") 作为 ARRAY ref
- python - python中有没有办法从2个列表中创建一个新列表,其中第一个列表值用于组成新列表的列表?
- ios - Keychain Swift 中的多个帐户