Are there cases where constexpr should be avoided, even it it could be used?

不羁的心 提交于 2019-12-04 03:34:48
TemplateRex

For variables, I don't see any reason not to use constexpr when you can. But it's not always possible to do so, e.g. when the initializer of a variable is computed by a virtual function e.g.

Adding constexpr to a function is an interface change: you are expressing the fact that you can use it to initialize constexpr variables. This imposes constraints on the implementation of your function, such as no calling of virtual functions, no dynamic memory allocations and no lambda functions as function objects.

Note that the resolution to LWG issue 2013 does not allow implementers of the Standard Library the freedom to add constexpr to library functions. One of the reasons is that declaring a function constexpr can inhibit certain debugging implementations that do dynamic allocations (notably iterator checking). This means that future expansions of constexpr to the Standard Library need to be separate proposals. This is in contrast to noexcept, where library writers have more freedom.

You can change a const:

int const x = 1;

*const_cast<int *>(&x) = 5;

You cannot do the same with constexpr, which allows the compiler to know without a doubt that the expression is available at compile time, and thus optimizations are possible.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!