用于创建对象的Constexpr [英] Constexpr for creating objects
问题描述
我试图找出使用 constexpr
创建对象(而不是正常创建对象)是否会提高性能。
I'm trying to figure out if there is a performance gain of creating objects with constexpr
instead of normally.
这是 constexpr
的代码段。
class Rect
{
const int a;
const float b;
public:
constexpr Rect(const int a,const float b)
: a(a),b(b){}
};
int main()
{
constexpr Rect rect = Rect(1,2.0f);
}
并且没有 constexpr
class Rect
{
int a;
float b;
public:
Rect(int a, float b)
: a(a),b(b){}
};
int main()
{
Rect rect = Rect(1,2.0f);
}
我期望 constexpr
,因为应该在编译时初始化内存。
I was expecting there will be a lot less code for constexpr
since the memory should be initialized at compile-time.
我使用 constexpr
正确吗?如果不是这样,可以使用 constexpr
在编译时创建对象,然后在没有任何运行时开销的情况下使用它们吗?
Am I using constexpr
properly? And if that is not true, can you use constexpr
to create the objects at compile-time and then use them without any runtime overhead?
谢谢!
推荐答案
事实证明,我包含一些标头,这些标头负责代码。
It turned out that I had some headers included which were responsible for the similarity of the code.
答案是两种情况之间有很大差异。
The answer is that there is a big difference between both cases.
在没有优化的情况下进行编译时,生成的代码中存在实质性差异 ...
-cdhowie
When compiling without optimizations, there is a substantial difference in the generated code... -cdhowie
这篇关于用于创建对象的Constexpr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!