I have the following code (include-guards omitted for simplicity’s sake):
= foo.hpp =
struct FOO
{
int not_used_in_this_sample;
int not_used_in_this_sample2;
};
= main.cpp =
#include "foo_generator.hpp"
#include "foo.hpp"
int main()
{
FOO foo = FooGenerator::createFoo(0xDEADBEEF, 0x12345678);
return 0;
}
= foo_generator.hpp =
struct FOO; // FOO is only forward-declared
class FooGenerator
{
public:
// Note: we return a FOO, not a FOO&
static FOO createFoo(size_t a, size_t b);
};
= foo_generator.cpp =
#include "foo_generator.hpp"
#include "foo.hpp"
FOO FooGenerator::createFoo(size_t a, size_t b)
{
std::cout << std::hex << a << ", " << b << std::endl;
return FOO();
}
This code, as it stands, compiles perfectly fine without any warning. If my understanding is correct, it should output:
deadbeef, 12345678
But instead, it randomly displays:
12345678, 32fb23a1
Or just crashes.
If I replace the forward-declaration of FOO in foo_generator.hpp with #include "foo.hpp", then it works.
So here is my question: Does returning a forward-declared structure lead to undefined behavior ? Or what can possibly go wrong ?
Compiler used: MSVC 9.0 and 10.0 (both show the issue)
That should be fine according to 8.3.5.6: “The type of a parameter or the return type for a function declaration that is not a definition may be an incomplete class type.”