Original Post
In Modern C++ Design (Alexandrescu), an example implementation of an object factory wraps a concrete object creator function and an ID in an anonymous namespace, to hide it from the rest of the programme. This practice, although effective, just seems inherently strange to me, but maybe this is a lack of experience on my part. Instinctively, I do not see why this could not be wrapped in a class instead, which is one of the purposes of a class or struct, to encapsulate and isolate the data and methods. Is it somehow safer to use anonymous namespaces? Is it more efficient when compared to alternatives? Are there situations where there is no choice? Any views? --random Edit--here is a simple example that illustrates my concern:
#include <iostream.h>
namespace
{
int local; // should not collide with other files
}
void func()
{
local = 2;
}
int main()
{
local = 1;
cout<< "local=" << local << endl;
func();
cout<< "local=" << local << endl;
return 0;
}
// results in
local=1
local=2
Is there any difference between unnamed namespaces and globals? [Edited by - random_thinker on September 11, 2007 5:48:23 AM]