For this code
struct test {};
test f() { return test(); }
void print(test *x) {}
int main()
{
print(&f());
print(&test());
}
gcc-4.6 emits two “taking address of temporary [-fpermissive]” errors. This was introduced in 4.6, gcc-4.5 could compile it.
The reason is pretty clear and well documented. The problem is that it is a legacy code and, to compile, we have to make it work, thus, doing #pragmas around files and/or parts of code to compile them with -fpermissive. Let’s say, customers are adamant not to modify the existing code (i.e. the fact of calling print() with &f() or &test() cannot be changed, not source files in general). In other words, one way or another this will be compiled, the only choice is more or less pain.
So the question is – are there any possible workarounds to make it work without doing -fpermissive in lots of places? -W flags, C++ tricks, etc.
If you have control over the type itself, you can always overload the reference operator,
operator&, and returnthisfrom it. It’s not a good thing to do in the general case, but it’s fairly safe considering that you’re returning the correct pointer of the correct type.If base classes are involved, then it becomes rather more complicated. You’ll need to use a virtual operator overload, and each class in the hierarchy will need to implement it separately.