Using noexcept with constexpr function

In Scott Meyers' Effective Modern C ++, he gives the following function to find the size of an array:

template<typename T, std::size_t N> constexpr std::size_t arraySize(T (&)[N]) noexcept { return N; } 

What is the purpose of "noexcept" here? As far as I understand, it not only affects the generation of runtime code, but I don’t see any situation where this function could be called at runtime rather than compiling time?

+7
c ++
source share
2 answers

In general, a template marked as constexpr may lose this status when instantiated. If a specific set of template arguments does not allow this, this qualification is silently deleted, and the generated function is "normal".

Most likely, this is indicated to teach you a good habit. Although it is true that the consexpr function is implicitly accepted without metalization, if the status of the constexpr function is removed, it will still not interfere with the correct noexcept specifications. When it is used as part of an expression that is supplied to the noexcept() operator.

If it had not been defined like this, it would have distorted the exception specifications of functions that use it in their application noexcept() . Because he considered potentially throwing without specification.

Since the noexcept() operator is also computed at compile time, this is not about generating code (as you formulated it). It is rather a matter of semantic correctness, akin to the correctness of the competition.

+5
source share

but I don’t see any situation where this function could be called at runtime rather than compiling time?

For example, simply:

 int a[42]; std::cout << arraySize(a); 

we are not in constant expression.

To force constexpr, you should use something like:

 int a[42]; constexpr auto size = arraySize(a); std::cout << size; 
0
source share

All Articles