c++ - 为什么要在构造函数上使用 constexpr?

我知道 constexpr 允许您在编译时将对象用作常量,但是什么时候这会有益呢?我试图更好地理解关键字,但我找不到一个很好的例子来解释为什么需要它的构造函数。

下面的两个例子都有效,那么为什么要将 constexpr 放在构造函数上呢?

在构造函数上使用 constexpr:

#include <iostream>
using namespace std;

class Rect
{
    public:
        constexpr Rect(int width, int height)
            : mWidth(width), mHeight(height) {}
        constexpr int getArea() const { return mWidth * mHeight; }
    private:
        int mWidth, mHeight;
};

int main(int argc, char* argv[])
{
    constexpr Rect r(8, 2);

    cout << r.getArea() << endl;   //16

    int myArray[r.getArea()];    // OK


    return 0;
}

在构造函数上没有 constexpr:

#include <iostream>
using namespace std;

class Rect
{
    public:
        Rect(int width, int height)
            : mWidth(width), mHeight(height) {}
        constexpr int getArea() const { return mWidth * mHeight; }
    private:
        int mWidth, mHeight;
};

int main(int argc, char* argv[])
{
    Rect r(8, 2);

    cout << r.getArea() << endl;   //16

    int myArray[r.getArea()];    // OK


    return 0;
}

 

最佳答案

 

在您的第二个示例中,int myArray[r.getArea()]; 在标准 C++ 中是不允许的,因为 r.getArea() 不是常量表达式。 (如果您的编译器接受它,那么您依赖于编译器扩展,并且如果您以符合模式调用编译器,应该会产生警告)。

如果将数组更改为:

std::array<int, r.getArea()> myArray;

编译器不太可能在非constexpr 版本中接受它。

 

关于c++ - 为什么要在构造函数上使用 constexpr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36489123/

 

posted @   imxiangzi  阅读(54)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示