Any reason to use a runtime statement instead of a compile time statement?

While viewing Visual C ++ codebase, I discovered the following strange thing. A run-time statement (which checks the condition and throws an exception if the condition is violated) was used when the condition could be evaluated at compile time:

assert( sizeof( SomeType ) == sizeof( SomeOtherType ) ); 

it is clear that the compiler will evaluate the condition and replace the code, which will be effective either

 assert( true ); 

which does nothing or

 assert( false ); 

which throws an exception every time control passes through this line.

IMO should use the compile-time statement for the following reasons:

  • he would detect a condition violation earlier - at compile time - and
  • this would allow the cleaner code to be emitted (thus faster and less)

The statement about compilation seems to be the only right thing. Is there any possible reason to prefer runtime?

+5
source share
2 answers

There is no reason to believe that runtime is approved here. You should prefer compile-time errors during runtime errors, so there is never a reason, given the option between the two, to choose a runtime statement.

However, if a static statement is not an option (does not know the concept of a static statement, does not know how to make it and does not have one available, or knows how to make it, but doesn’t have time), the statement about the execution time is the next best thing.

With C ++ 0x, the built-in static_assert function should stop all the reasons for using the run-time statement in which the compilation request will run.

+15
source

We cannot say without context. In the template code, some branches may not be available for some instances. A statement of compilation time would be inappropriate, as this makes the entire function informal. assert(<type-dependent expression>) no.

eg.

 template <typename T> void foo(T t) { if (t < 0) { assert(std::numeric_limits<T>::min() < 0); T u = t - std::numeric_limits<T>::min(); } } 

A statement cannot be converted to a static statement, even if the run-time statement never completes.

+4
source

Source: https://habr.com/ru/post/893565/


All Articles