首页 > 解决方案 > 静态 constexpr 变量和局部 constexpr 变量有什么区别

问题描述

鉴于以下 2 个程序,使用静态 constexpr 变量和局部变量有什么区别

方案一:

class point
{
public:
    constexpr point() = default;
    constexpr point(int x, int y) : x_{x}, y_{y}{}
    constexpr point(point const&) = default;
    constexpr point& operator=(point const&) = default;
    constexpr int x() const noexcept { return x_;}
    constexpr int y() const noexcept { return y_;}
private:
    int x_{};
    int y_{};
};

constexpr point increment_both(point p){
   return {p.x() + 1, p.y() + 1};
}

constexpr point add(point a, point b){
    return {a.x() + b.x(), a.y() + b.y()};
}

constexpr point origin{};
constexpr point pp{33,4};
constexpr point iipoint = increment_both(pp);
constexpr point r = add(pp, iipoint);
constexpr int v = r.x();

int main()
{
    return v;
}

程序清单 2:

class point
{
public:
    constexpr point() = default;
    constexpr point(int x, int y) : x_{x}, y_{y}{}
    constexpr point(point const&) = default;
    constexpr point& operator=(point const&) = default;
    constexpr int x() const noexcept { return x_;}
    constexpr int y() const noexcept { return y_;}
private:
    int x_{};
    int y_{};
};

constexpr point increment_both(point p){
   return {p.x() + 1, p.y() + 1};
}

constexpr point add(point a, point b){
    return {a.x() + b.x(), a.y() + b.y()};
}

int main()
{

    constexpr point origin{};
    constexpr point pp{33,4};
    constexpr point iipoint = increment_both(pp);
    constexpr point r = add(pp, iipoint);
    constexpr int v = r.x();

    return v;
}

程序清单 1:这在未优化时发出的代码更少。主要的:

push    rbp
mov     rbp, rsp
mov     eax, 67
pop     rbp
ret

程序 2 发出一个更主要的堆:

push    rbp
mov     rbp, rsp
mov     DWORD PTR [rbp-12], 0
mov     DWORD PTR [rbp-8], 0
mov     DWORD PTR [rbp-20], 33
mov     DWORD PTR [rbp-16], 4
mov     DWORD PTR [rbp-28], 34
mov     DWORD PTR [rbp-24], 5
mov     DWORD PTR [rbp-36], 67
mov     DWORD PTR [rbp-32], 9
mov     DWORD PTR [rbp-4], 67
mov     eax, 67
pop     rbp
ret

这些之间有什么区别。使用一个比另一个更好吗?以及为什么汇编程序输出存在巨大差异。

谢谢。

标签: c++constexpr

解决方案


推荐阅读