C++ 在发布模式下 assert(false) 是否被忽略?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/270488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:12:02  来源:igfitidea点击:

Is assert(false) ignored in release mode?

c++visual-c++posixassert

提问by Brian R. Bondy

I am using VC++. Is assert(false)ignored in release mode?

我正在使用 VC++。assert(false)在发布模式下被忽略?

回答by activout.se

If compiling in release mode includes defining NDEBUG, then yes.

如果在发布模式下编译包括定义 NDEBUG,则是。

See assert (CRT)

请参阅断言 (CRT)

回答by Harper Shelby

IIRC, assert(x) is a macro that evaluates to nothing when NDEBUG is defined, which is the standard for Release builds in Visual Studio.

IIRC,assert(x) 是一个宏,当定义 NDEBUG 时,它的计算结果为零,这是 Visual Studio 中发布版本的标准。

回答by grieve

The assert macro (at least it is typically a macro) is usually defined to no-op in release code. It will only trigger in debug code. Having said that. I have worked at places which defined their own assert macro, and it triggered in both debug and release mode.

assert 宏(至少它通常是一个宏)通常在发布代码中定义为 no-op。它只会在调试代码中触发。话说回来。我曾在定义了自己的断言宏的地方工作过,它在调试和发布模式下都被触发。

I was taught to use asserts for condition which can "never" be false, such as the pre-conditions for a function.

我被教导对“永远”不为假的条件使用断言,例如函数的前置条件。

回答by Rob

Only if NDEBUG is defined I think (which it will be by default for Visual C++ apps).

仅当我认为定义了 NDEBUG(Visual C++ 应用程序的默认设置)。

回答by Ned Batchelder

I think it is a mistake to rely too much on the exact behavior of the assert. The correct semantics of "assert(expr)" are:

我认为过分依赖断言的确切行为是错误的。“assert(expr)”的正确语义是:

  • The expression expr may or may not be evaluated.
  • If expr is true, execution continues normally.
  • If expr is false, what happens is undefined.
  • 表达式 expr 可能会也可能不会被计算。
  • 如果 expr 为真,则执行正常继续。
  • 如果 expr 为假,发生的事情是不确定的。

More at http://nedbatchelder.com/text/assert.html

更多信息请访问http://nedbatchelder.com/text/assert.html

回答by RzR

same for GNU :

GNU 相同:

  #ifdef    NDEBUG

  # define assert(expr)     (__ASSERT_VOID_CAST (0))