5
我想弄清楚是否有性能增益与constexpr
而不是通常创建对象。Constexpr创建对象
这是constexpr
的代码片段。
class Rect
{
const int a;
const float b;
public:
constexpr Rect(const int a,const float b)
: a(a),b(b){}
};
int main()
{
constexpr Rect rect = Rect(1,2.0f);
}
并且没有constexpr
。
class Rect
{
int a;
float b;
public:
Rect(int a, float b)
: a(a),b(b){}
};
int main()
{
Rect rect = Rect(1,2.0f);
}
我期待会有少了很多代码为constexpr
,因为内存应该在编译时被初始化。
我正在使用constexpr
吗?如果这不是真的,你可以使用constexpr
在编译时创建对象,然后使用它们而没有任何运行时开销?
谢谢!
_“的constexpr指定符,它是__possible__评估在编译时函数或变量的值” _来源:http://en.cppreference.com/w/cpp/language/constexpr。并不是说它需要在编译时进行评估。尝试更改'Rect rect = Rect(1,2.0f);'为'constexpr Rect rect {1,2.0f};' –
为什么downvote?这是写得很好,*不*明显(至少,不是我)。 – Bathsheba
我的意思是,当你开启优化时没有什么区别,因为你不用'rect'做任何事情,所以[它会被删除](https://godbolt.org/g/hQxTnU)是否或不是你用'constexpr'。你无法比没有代码更有效率! – cdhowie