c++ - 静态 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
这些之间有什么区别。使用一个比另一个更好吗?以及为什么汇编程序输出存在巨大差异。
谢谢。
解决方案
推荐阅读
- reflex - 前端类型的 Monadwidget
- r - Str_Extract 问题:缺少模式
- c++ - 如何使用抽象对象数组?无效的抽象类型错误
- android - Facebook connect Android - 生成无过期令牌
- php - 如何编写基于用户角色的重定向?
- swift - Swift:无法释放内存
- java - 我们期望 Ignite 什么时候触发 EVT_CACHE_ENTRY_CREATED 和 EVT_CACHE_OBJECT_PUT 事件
- css - 在悬停和聚焦时更改 Mat Expansion 中内容的颜色
- android - 代号一键盘封面图片
- ruby - 如何使用带有 RSpec 模拟的冰糕类型检查?