std::function
provides more flexibility than raw function pointers but comes with some overhead. Let's examine the differences and when each might be appropriate.
Function pointers are simple and lightweight:
class Player {
public:
using FnPtr = void(*)(int NewHealth);
void SetDelegate(FnPtr Fn) {
OnDamage = Fn;
}
void TakeDamage(int Damage) {
Health -= Damage;
if (OnDamage) OnDamage(Health);
}
private:
FnPtr OnDamage{nullptr};
int Health{100};
};
void LogHealth(int NewHealth) {
std::cout << "Health: " << NewHealth << '\n';
}
int main() {
Player P;
P.SetDelegate(LogHealth);
P.TakeDamage(30);
}
std::function
std::function
is more flexible but has overhead:
class Player {
public:
using Delegate = std::function<
void(int NewHealth)>;
void SetDelegate(Delegate D) {
OnDamage = D;
}
void TakeDamage(int Damage) {
Health -= Damage;
if (OnDamage) OnDamage(Health);
}
private:
Delegate OnDamage;
int Health{100};
};
int main() {
Player P;
// Can store free functions
P.SetDelegate(LogHealth);
// Can store lambdas with capture
int LogCount{0};
P.SetDelegate([&LogCount](int NewHealth) {
std::cout << "Health: " << NewHealth << '\n';
LogCount++;
});
P.TakeDamage(30);
}
Use raw function pointers when:
Use std::function
 when:
Remember that premature optimization is the root of all evil. Start with std::function
for its flexibility, and only switch to raw function pointers if profiling shows it's necessary for your specific use case.
Answers to questions are automatically generated and may not have been reviewed.
An overview of the options we have for building flexible notification systems between game components