静态constexpr变量和局部constexpr变量之间有什么区别

时间:2019-03-11 14:58:50

标签: c++ constexpr

给出以下两个程序,使用静态constexpr变量和局部变量有什么区别

程序1:

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

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

谢谢。

0 个答案:

没有答案
相关问题