c++ - 为什么需要仅在全局命名空间中包含 vector (以及其他 header )?

标签 c++ stl include new-operator

这是我的示例代码及其输出。

namespace AAA
{
#include <vector>
}

int main()
{
    AAA::std::vector<int> vec;

    return 0;
}

/usr/include/c++/4.9/new:129:41: error: 'void* AAA::operator new(AAA::std::size_t)' may not be declared within a namespace
   __attribute__((__externally_visible__));
  1. 为什么不允许在命名空间中声明 new/delete 运算符?
  2. 标准是否要求包含 <vector> (以及其他 header )来自全局命名空间?

最佳答案

是的,该运算符必须在全局范围内。它很“特别”。

[C++14: 3.7.4.1/1]: An allocation function shall be a class member function or a global function; a program is ill-formed if an allocation function is declared in a namespace scope other than global scope or declared static in global scope. [..]

而且,是的,标准库头文件必须在“可用空间”中#include:

[C++14: 17.6.2.2/3]: A translation unit shall include a header only outside of any external declaration or definition, and shall include the header lexically before the first reference in that translation unit to any of the entities declared in that header. No diagnostic is required.

关于c++ - 为什么需要仅在全局命名空间中包含 vector (以及其他 header )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39961314/

相关文章:

C 内核库包含和膨胀

c++ - 如何在重命名函数(c++)中使用变量?

c++ - 使用 C++ 和 jsoncpp 将文件行写入 JSON

c++ - 当使用 _ENABLE_PER_THREAD_LOCALE 时,STL 对象使用 C 运行时库语言环境进行浮点转换?

c++ - 非递归 Kosaraju 的两遍算法实现永远在大型数据集上执行

c++ - VC9 中的字符串流错误? "Cannot access private member"

c++ - boost 目录以包含访问者设计模式

c++ - SIMD/SSE : short dot product and short max value

c++ - 如何在不使用 const 的情况下防止删除指针?

c++ - 循环包含,我如何在不改变类层次结构的情况下解决这个问题