gpt4 book ai didi

c++ - 我可以停止 GCC 将标准库名称包含到全局 namespace 中吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:34:28 26 4
gpt4 key购买 nike

当我在 C++ 中使用标准 C 头文件时,我通常更喜欢将标识符放入 std 中的形式。命名空间,例如 <cstdlib> .然而,当我使用这些时,GCC 也会将名称放入全局命名空间,这意味着它将接受如下程序:

#include <cstddef>

std::size_t x;
size_t y;

int main() {}

在这里,x 的声明是正确的,但是 y 的声明如果我希望我的代码可移植,应该被拒绝。 (请注意,如果我包含 <stddef.h> 而不是 <cstddef>,GCC 正确地拒绝 x 的声明)。

我能否让 GCC 拒绝声明 y以上?

我编译了所有我能想到的迂腐和警告:

-std=c++17 -pedantic -Wall -Wextra -Wpedantic -Weffc++

这些似乎都不能阻止 GCC 接受不可移植的形式。


我现在不确定我是否正确理解规则;我的知识来自 CPP 引用中的这一部分:

C compatibility headers

For some of the C standard library headers of the form xxx.h, the C++ standard library both includes an identically-named header and another header of the form cxxx.

With the exception of complex.h, each xxx.h header included in the C++ standard library places in the global namespace each name that the corresponding cxxx header would have placed in the std namespace.

These headers are allowed to also declare the same names in the std namespace, and the corresponding cxxx headers are allowed to also declare the same names in the global namespace: including <cstdlib> definitely provides std::malloc and may also provide ::malloc. Including <stdlib.h> definitely provides ::malloc and may also provide std::malloc. This applies even to functions and function overloads that are not part of C standard library.

对我来说,最后一段表明 GCC 的行为是允许的但不是必需的,因此依赖它是错误的。

最佳答案

规则是 #include <xxx.h>(其中 xxx.h 是标准 C header 的名称)需要来为全局命名空间中的该 header 定义 C 标准所需的所有名称,并且 < strong>allowed 在命名空间 std 中也定义这些名称(具有相同的含义)。类似地,#include <cxxx>(其中 cxxx 是标准 C 库的标准 C++ 头文件之一的名称)需要定义命名空间中相应 C 头文件(具有相同含义)的所有名称std ,并且允许在全局命名空间中定义这些名称。

在 C++ 98 中,这些 header 不允许将名称添加到其他命名空间。一些编译器无法做到这一点。例如,如果 C++ 库编写者不控制 C header ,通常的实现技术是将 C++ header 指向 #include C header ,并使用 using 声明将 C 名称提升到 std。因此更改了规则以反射(reflect)现实。

语言定义要求这些 header 将名称放在两个地方;如果是,则不需要 cxxx header 。

简而言之,您不能指望 #include <cxxx> 将 C 名称放入全局命名空间,但您也不能指望它不将它们放在那里。

关于c++ - 我可以停止 GCC 将标准库名称包含到全局 namespace 中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44694574/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com