namespace
{
class sample_class { /* class body */ };
}
This cannot be achieved by using the static keyword.
While it is certainly true that the static keyword cannot be used in this case, I fail to see what you achieve by putting sample_class in an unnamed namespace. If you write a class definition in a .cpp file, there is (I believe) no way to access it from another .cpp file, regardless of whether it is placed in an unnamed namespace or not.
So what benefit does the unnamed namespace actually give?
If a definition is not inside an unnamed namespace the linker will try to link it to other symbols with the same name even if those are in other source files
I do not see the linker trying to link the names of classes the way you describe.
Consider these two pieces of code:
File 1:
1 2 3 4 5 6 7 8 9
class Alpha {
public:
int i;
};
int main()
{
Alpha a;
}
File 2:
1 2 3 4 5 6 7 8
void Alpha()
{
}
void xx()
{
Alpha();
}
Although the symbol "Alpha" is defined in both files, I have no problem compiling and linking these files together. (I've tried both with GNU's and Microsoft's compiler.)
Yes, if Alpha is a function or a variable in both files, the linker will complain, but that problem can be solved with "static". So I still want to know: What does an unnamed namespace give me?
Can anybody show me a piece of code that will not work without unnamed namespaces and which cannot be solved equally well using "static"?
// file 2
class S
{
void foo();
};
void S::foo()
{
// something else
}
Result:
/tmp/ccvDdNNj.o: In function `S::foo()':
/home/bazzy/file2.cpp:7: multiple definition of `S::foo()'
/tmp/ccrSkKSi.o:/home/bazzy/file1.cpp:4: first defined here
collect2: ld returned 1 exit statu
BTW in C++ the use of static for this purpose has been deprecated