|
-
August 9th, 2005, 05:56 AM
#4
Re: What is the Global Namespace
 Originally Posted by ireland
Thanks,
So I have come across topics recommending not using the global namespace and global namespace pollution, is this because of the possibility of naming conflicts or is there some other reason? Surely the compiler would pick these conflicts up!
Can you create objects on the heap from the global namespace, and it so where are they/should they be deleted?
The global namespace is "the area" surrounding any namespaces declared explicitely, regardless whether these are named or not. The purpose of namespaces is to group together things that logically belong together. Because of this, if you bloat a namespace into the global namesace (a.k.a "pollute the global namespace") you distroy this logical grouping. As a side effect, the compiler won't be able any more to distinguish between constructs that have the same name but belonged to different namespaces. In most cases the compiler will pick the conflict up and generate an error but there are cases where the compiler will be able to solve the conflict on its own in a way unintended by the programmer. This leads to hard to track bugs. Example:
Code:
namespace my_namespace
{
void f(int i)
{
// do something
}
}
void f(float x)
{
// do something else);
}
//version 1:
using namespace my_namespace;
// version 2: comment out the above line
int main()
{
f(1); // version 1: will call my_namespace::f(1), because it's the better match
// version 2: will call the f(1) in the global namespace
return 0;
}
Creating objects (on the free store -- a.k.a. heap -- or otherwise) has nothing to do with namespaces. If you say the compiler will search for the type "A" beginning with the innermost namespace (the one where your line of code lives in) up to the global namespace and pick the first A that qualifies. The heap itself doesn't know about namespaces at all.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|