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

发布时间 2023-05-16 18:14:20作者: imxiangzi

我知道 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/