Constexpr for creating objects

流过昼夜 提交于 2019-12-10 13:55:48

问题


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

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