Prevent standard functions outside of std namespace

前端 未结 5 656
梦如初夏
梦如初夏 2021-01-04 01:51

I am using only header files specific to C++ (e.g. ), however I still get globally-declared functions, and not just functions in the std

5条回答
  •  醉梦人生
    2021-01-04 02:19

    1. will always populate std namespace, and sometimes define global symbols, while will always define global symbols, and sometimes populate std namespace. This varies from implementation to implementation.

    2. The standard writes:

      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. It is unspecified whether these names are first declared or defined within namespace scope (3.3.6) of the namespace std and are then injected into the global namespace scope by explicit using-declarations (7.3.3).

      Which means, that the compiler is allowed to put those symbols into global scope and std namespace at the same time.

    3. Therefore, we see no advantages to prefer one header file over the other. Because they are both very likely to pollute the global scope.

      However, it is still necessary to use std namespace when #include , and do not use std when #include , to make sure your code can compile for all compiler implementations.

    4. Advice: Do not use names in standard libraries. First, they are not guaranteed to work. (Note: Few compiler implementations actually keep the global scope clean when you #include , so never depend on this.) Second, it will confuse code readers and maintainers, because almost everyone will assume standard names are actually standard, no matter where they come from.

提交回复
热议问题