void DoSomething()
{
//Something is done here ;)
}
class Base
{
public:
Base(void (*function)()) : function(function) {}
void (*function)();
};
class Derived : public Base
{
public:
Derived() : Base(DoSomething) {}
};
Do you thing a compiler can optimize this so that Derived doesn't keep the function pointer in memory, but uses it as any other normal function? I personally think it will be possible since function won't be changed in Derived, but what do you guys think?
Why not? Maybe not in this case, but function pointers keep the pointer in memory per object right? And if I remember it right, class functions are usually inlined, and if not, at least it is not in memory per object.
Class function are inlined only if defined in the class body and the compiler decides to inline them
How member functions are stored and how objects access them is nod defined in the C++ standard
Wait a minute... I think everyone missed the subtle question.
When you call a function by name, the compiler generates a single CALL instruction (assuming intel) to
some memory location that is essentially known either at compile time or fixed up at load time by
the OS loader.
When you call a function by pointer, first the compiler has to generate code to read the memory
locations containing the function's address into a register, then generate a single CALL instruction to
the value stored in the register. That's 2 instructions (at least) vs. 1 above.
OP is asking can the compiler, through optimizations, turn this second case into the first one. The
answer is absolutely positively not under any circumstances. This is one of the performance benefits
to using templates, inlines, and function objects. In that case, yes, the compiler can avoid the second
case because it knows what function to call at compile time.
That depends. If the function pointer is in a local variable on the stack or a parameter to the function, yes.
If the function pointer were a member of a struct, it may require more.