constexpr
values whenever it is possibleconstexpr
is a good way to ensure that values remain constant, and variables that are constexpr
are constant expressions*.
As a general rule, default to constexpr
unless something can only be known at run-time. vector
and string
always require run-time knowledge, so they cannot be const
.
*Recommending constexpr
does not mean explaining what a constant expression is. This is a separate discussion. For now, we can say "known at compile time".
const
whenever you can’t use constexpr
const
lets us reason about our programs with security and helps us produce more declarative code. Rather than suggesting that const
is applied when you know that a value won’t (or can’t) change, offer const
as the default, and suggest students remove const
when they encounter a reason to mutate the variable.
Editor’s note: [types.const.const] does not suggest introducing lambda-initialisation (IILE).
Editor’s note: [types.const.const] becomes more and more easy-to-use when ranges are incorporated into a program.
--Hi,this post is inspired by a presentation of one committee member posted recently on reddit.I have no doubts there is a lot of good thoughts and engineering behind the works. But this group should discuss suitability for teaching or approaching students and other c++ programmers. I would say discussing new proposals from teach-ability perspective should be one of the most important things for this group. It's arguably more important than new guidelines and material - that can be done any time and people do it already - but once a new complicated or difficult to teach feature is included in the standard there is no way to remove it and so we should better get it right.So I have a question. Do you really think constant variables/functions/initialization is going in the right direction? Most c++ programmers I know are using only pre-c++11 const keyword. Few understand constexpr variables and functions. How many of them do you think will be using new keywords in this area - consteval, constinit, is_constant_evaluated when it becomes available? Doesn't this work solve niche problem? Do you think so many new keywords for constant initialization will not be a burden to newcomers and average c++ programmers?I am really interested in what this group thinks of it.
SG20 mailing list
SG20@lists.isocpp.org
http://lists.isocpp.org/mailman/listinfo.cgi/sg20