Monday C++ Quiz: We Are All Confused
There is a whole bunch of super smart C++ types in the office talking about a strange little C++ program, which I'm turning into an emergency quiz.
Q: Should the following C++ program compile? link? run without core dumps? And if so, what does it output?
namespace A {
class F {
public:
static F f;
F() {}
void bar() { }
};
};
namespace {
A::F::F f;
}
void foo() {
A::F &myF = A::F::f;
myF.bar();
}
int main() {
return 0;
}
Re: Monday C++ Quiz: We Are All Confused
Ok, maybe that was unfair...
I'm going to guess that it won't compile, because f is never defined.
Did you mean for the code inside the anonymous namespace to be "A::F::f" or even "A::F A::F::f"?
That still doesn't make sense because f lives inside namespace A, so it doesn't make sense to try to define it inside an anonymous namespace.
Can you use "inline" with fields?
Oh well, if I missed the point, I chalk it up to not having really used C++ for quite a while now.
Re: Monday C++ Quiz: We Are All Confused
Try it with GCC and you'll find a surprise... I verified with the Comeau online compiler that this is not valid C++.
Interestingly, the initial code fragment not only compiled in GCC but also had the same overall effect as what the author intended -- it created an anon namespace object which could be referenced the same way the class-scoped static could.
Re: Monday C++ Quiz: We Are All Confused
A simple query on the gcc mailing list leads to this gcc bug report.
Re: Monday C++ Quiz: We Are All Confused
The anonymous namespace has ___nothing___ to do with this since it is invalid C++. But let's get to it, first, with your example:
g++ 4.3.2 : /tmp/ccIYjJxr.o: In function `foo()': coredumper.cc:(.text+0xc): undefined reference to `A::F::f' collect2: ld returned 1 exit statusicc 10.1.018: compiles & runs (that's an error intel guys, you don't do it right). That bug report is against g++ 3.3.2, and there is code to make your example "pass" with 4.3.2 as well, but it is off topic. Take a look at this example and see why you don't have namespace issues:
#include <cstdio>
namespace A {
class F {
public:
static F f() { return F(); }; // static function signature
F() { printf("hello\n");};
void bar() const { printf("you called bar..\n"); };
};
}
namespace {
A::F f() { return A::F(); }
}
void foo() {
A::F const& myF = f(); // const reference
myF.bar();
}
int main() {
foo();
return 0;
}
Compiles and runs under g++4.3.2, icc10.1.018 and visual studio 2008 C++. Online Comeau C/C++ 4.3.10.1 test passed.
The anonymous namespace has nothing to do with this (we are in the same translation unit), the ill defined struct and the erroneous use of references are to blame.
You got my email, see you :)