Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use of noexcept with constexpr function

Tags:

c++

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 the 'noexcept' here? As I understand it, noexcept only affects the generation of run time code - but I can't see any situation where this function could be called at run time rather than compile time?

like image 684
Sir Visto Avatar asked Oct 17 '17 17:10

Sir Visto


1 Answers

In the general case, a template marked as constexpr may lose that status when instantiated. If a particular set of template arguments doesn't allow it, that qualification is silently removed, and the generated function is a "regular" one.

It's most likely specified like that to teach you a good habit. While it's true that a consexpr function is implicitly assumed non-throwing, if the constexpr status of the function is removed, it would still not interfere with correct noexcept specifications. When it's used as part of the expression being fed to the noexcept() operator.

Had it not been defined like that, it would skew exception specifications of functions that use it in their application of noexcept(). Because it's considered potentially throwing without the specification.

Since the noexcept() operator is evaluated at compile time too, it's not about code generation (as you phrased it) at all. It's more a matter of semantic correctness, akin to const correctness.

like image 62
StoryTeller - Unslander Monica Avatar answered Oct 08 '22 14:10

StoryTeller - Unslander Monica