在标准命名空间中声明名称的坏习惯? [英] Bad practice to declare names in the standard namespace?

查看:169
本文介绍了在标准命名空间中声明名称的坏习惯?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我浏览了 Google C ++风格指南,发现了这个问题:

I was looking through the Google C++ style guide, and came across this:

不要在命名空间std中声明任何内容,甚至不能声明标准库类的声明。在命名空间std中声明实体是未定义的行为,即不可移植。标准库,包括适当的头文件。

"Do not declare anything in namespace std, not even forward declarations of standard library classes. Declaring entities in namespace std is undefined behavior, i.e., not portable. To declare entities from the standard library, include the appropriate header file."

有人可以解释这意味着什么,为什么这是未定义的行为使用示例代码?

Could someone explain what this means and why this is undefined behavior using example code?

推荐答案


有人能解释这意味着什么,为什么这是未定义的行为使用示例代码? p>

Could someone explain what this means and why this is undefined behavior using example code?

以下程序产生未定义的行为:

The following program yields undefined behavior:

namespace std {
    void foo(int) { }
}

#include <iostream>

int main() {
    std::cout << "Hello World!" << std::endl;
}

为什么?它在命名空间 std 中声明了一个名为 foo 的函数。至于为什么这会导致一个问题,考虑:标准库实现可能有自己的函数 foo(),并且可能由< iostream> 。您的 foo 可能是比标准库实现的 foo 更好的匹配。

Why? It declares a function named foo in namespace std. As for why this could cause a problem, consider: the Standard Library implementation might have its own function named foo() and that might be used by some component in <iostream>. Your foo might then be a better match than the Standard Library implementation's foo.

这篇关于在标准命名空间中声明名称的坏习惯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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