Hello,
it's about functions without any side effect..
I know, that compiler are allowed to do some optimizations in the creation of return values, which change program behaviour.
1 2 3 4 5 6 7 8
|
struct Foo { Foo(){ cout << "foo"; } };
Foo foo() { return Foo(); }
int main()
{
Foo f = foo();
}
|
May print "foo" one or two times on the screen. As far as I know, unfortunately it is not allowed for the compiler to detect that "f" is unused, ommiting it completely and not print "foo" at all. Of course, in some cases this is a good thing. RAII would not work anymore..
But in some places I would like to tell my hard-working compiler: "It's fine. no RAII here.. There are no side effects at all! Don't hold back. Go for it! Optimize everything.."
The same seems to become worse for parameter construction calls. Consider this:
1 2 3 4 5 6 7 8
|
struct Bar { Bar(){ cout << "bar"; } };
void bar(Bar b) {}
int main()
{
bar( Bar() );
}
|
In this case, it is not allowed for a compiler to recognize that bar does nothing, inline it and finally throw away the function call and parameter construction completely and NOT printing out "bar". But why not?
Anyone know (probably non-portable) tricks to tell the compiler that he may safely skip parameter constructions and unused object creation like the one above? (Especially for the VC compilers)? Of course, a portable one involving some template or macro magic would be appreciated too :-D
By the way: It's not only about the constructor. Consider this example:
1 2 3 4 5 6 7 8
|
struct Baz { Baz operator!(){ cout << "baz"; return *this; } };
void baz(Baz b) {}
int main()
{
baz( !Baz() );
}
|
Not only the constructor should be "skipable", but the whole parameter construction, including construction of "unused parameters". I know that there is probably a lot of code which doesn't work in presence of such optimization. So if there's a trick to enable this for only some parts of the code, this would be even more appreciated.. (Compile-unit granularity would be perfect)
If there is nothing alike, wouldn't this make a very good addition to the standard? Something like an "optimizable" keyword or "nosideeffects" to parameter/functions/classes?
1 2 3 4 5 6 7 8 9 10 11
|
// Compilers are allowed to *not* create Foo objects or allowed to not
// call member functions of Foo if he detects that the results are not used
optimizable struct Foo {...};
// Compilers are allowed to omit the call to this function, if the return
// value is unused
optimizable int bar();
// Compilers are allowed to not create the first parameter, if it turns out
// to be unused in the function
int baz(optimizable Foo f, int b);
|
Ciao, Imi.
PS: For cl.exe, I've looked through the compiler options and didn't find any obvious switch, except maybe "/LTCG" but this looks like something less harmful...