在什么情况下我们应该包含cassert?
最佳答案
简而言之,不要使用它;使用 <assert.h>
.
C++11 删除了“c....” header 不会污染全局命名空间的任何形式保证。
这从来都不是实际保证,现在甚至不是正式保证。
因此,对于 C++11,使用“c....” header 变体不再有任何可以想象的优势,而与一个编译器及其版本一起工作的代码存在明显而明显的缺点编译器,可能无法使用其他编译器或版本编译,例如全局命名空间中的名称冲突或不同的重载选择。
所以,而 cassert
在 C++03 中是毫无意义的(你不能将宏放在命名空间中),在 C++11 中它完全没有意义——即使作为一般方案的特例。
附录,2013 年 12 月 22 日:
标准根据
C++11 §D.5/2:
“Every C header, each of which has a name of the form
name.h
, behaves as if each name placed in the standard library namespace by the corresponding cname header is placed within the global namespace scope.”
C++11 §D.5/3(非规范示例):
“The header
<cstdlib>
assuredly provides its declarations and definitions within the namespacestd
. It may also provide these names within the global namespace. The header<stdlib.h>
assuredly provides the same declarations and definitions within the global namespace, much as in the C Standard. It may also provide these names within the namespacestd
.”
堆栈溢出用户 C.R.的评论让我意识到某些版本的 g++,例如 MinGW g++ 4.7.2,相对于 <X.h>
是非常非标准。 header ,缺少例如的重载sin
C++ 标准要求:
我已经知道MinGW g++ 4.7.2也完全没有swprintf
等功能,并且它在纯 C++ 库中也有同样的缺点,例如缺少 C++11 std::to_string
.然而,关于它缺少 C 函数重载的信息对我来说是新的。
在实践中,g++ 缺少重载意味着
忽略 g++ 问题,或
避免使用缺少的 g++ 重载,
例如仅使用double sin( double )
, 或使用
std
命名空间重载
(然后需要包含<cmath>
以保证它们在 g++ 中的存在)。
为了使用 g++ std
命名空间重载不合格,一种实用的方法是为此编译器定义 headers wrappers。我已经使用这种方法来解决 g++ 的缺点。到printf
家庭。正如 David Wheeler 曾经说过的那样,“计算机科学中的所有问题都可以通过另一个层次的间接性来解决”……
然后可以安排事情,以便使用 g++ 缺失重载的标准代码也可以使用 g++ 编译。这会将编译器调整为标准,并使用固定数量的代码。
关于c++ - 在什么情况下我们需要包含<cassert>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10625716/