问题
I'm trying to figure out if there is a performance gain of creating objects with constexpr
instead of normally.
Here is the code snippet for 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);
}
And without 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);
}
I was expecting there will be a lot less code for constexpr
since the memory should be initialized at compile-time.
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?
Thanks!
回答1:
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.
When compiling without optimizations, there is a substantial difference in the generated code... -cdhowie
来源:https://stackoverflow.com/questions/44678277/constexpr-for-creating-objects