user1289 user1289 - 1 year ago 58
C++ Question

Why it's required to include vector (and other headers too) in global namespace only?

This is my sample code and its output.

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

  1. Why isn't allowed to declare operator new/delete in a namespace?

  2. Does standard require to include
    (and other headers too) from global namespace?

Answer Source

Yes, this operator must be at global scope. It is "special".

[C++14:]: 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. [..]

And, yes, standard library headers must be #included in "free space":

[C++14:]: 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.