任何理由使用运行时断言而不是编译时断言? [英] Any reason to use a run-time assert instead of compile-time assert?

查看:213
本文介绍了任何理由使用运行时断言而不是编译时断言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在查看Visual C ++代码库时,我发现了一个很奇怪的事情。在编译时可以评估条件的情况下使用运行时断言(如果条件被违反则检查条件并抛出异常):

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

清楚地,编译器将评估条件并替换实际上是

  assert(true); 

不执行任何操作,或

  assert(false); 

每当控件通过该行时都会抛出异常。



IMO应该使用编译时断言,原因如下:







  • $ b

    看起来像编译时断言是唯一正确的事情。有没有可能的理由喜欢这里的运行时断言?

    解决方案

    没有理由喜欢运行时断言。你应该更喜欢编译时错误超过运行时错误,所以没有一个理由,给定两者之间的选择,选择一个运行时断言。



    但是,如果一个静态断言不是一个选项(不知道静态断言的概念,不知道如何使一个可用,或者知道如何使一个可用,但没有时间



    对于C ++ 0x,内置的 static_assert 功能应该终止所有原因使用运行时断言其中编译时断言将工作。


    While reviewing Visual C++ codebase I found a following strange thing. A run-time assert (which is check the condition and throw an exception if the condition is violated) was used in a case when the condition could be evaluated at compile time:

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

    clearly the compiler will evaluate the condition and replace the code that will effectively be either

    assert( true );
    

    which does nothing or

    assert( false );
    

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

    IMO a compile-time assert should have be used instead for the following reasons:

    • it would expose the condition violation earlier - at compile time - and
    • it would let cleaner (thus faster and smaller) machine code be emitted

    Looks like a compile-time assert is the only right thing. Is there any possible reason to prefer a run-time assert here?

    解决方案

    There's no reason to prefer a run-time assert here. You should prefer compile-time errors over run-time errors so there's never a reason, given the option between the two, to choose a run-time assert.

    However, if a static assert isn't an option (doesn't know the concept of a static assert, doesn't know how to make one and doesn't have one available, or knows how to make one but doesn't have the time to), a run-time assert is the next best thing.

    With C++0x, the built-in static_assert feature should end all reason to use a run-time assert where a compile-time assert would work.

    这篇关于任何理由使用运行时断言而不是编译时断言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆