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

4 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;
}
Run Code Online (Sandbox Code Playgroud)

没有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;
}
Run Code Online (Sandbox Code Playgroud)

M.M*_*M.M 8

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

如果将阵列更改为以下内容,差异可能会更明显:

std::array<int, r.getArea()> myArray;
Run Code Online (Sandbox Code Playgroud)

编译器不可能在非constexpr版本中接受.

  • 这不回答这个问题. (2认同)
  • @LightnessRacesinOrbit 我认为确实如此。如果您不同意,也许您可​​以发布自己的答案 (2认同)