mirror of
https://github.com/wpilibsuite/allwpilib
synced 2026-06-20 00:51:42 +00:00
[commands] C++: Allow CommandPtrs to be owned by the scheduler (#7310)
Previously users would have to keep track of dynamically created CommandPtrs. This adds an ownership-taking version of schedule which places the command in a temporary store in the scheduler. The command will be freed when the command's lifecycle ends.
This commit is contained in:
@@ -62,6 +62,11 @@ class CommandScheduler::Impl {
|
||||
wpi::SmallVector<Command*, 4> toCancelCommands;
|
||||
wpi::SmallVector<std::optional<Command*>, 4> toCancelInterruptors;
|
||||
wpi::SmallSet<Command*, 4> endingCommands;
|
||||
|
||||
// Map of Command* -> CommandPtr for CommandPtrs transferred to the scheduler
|
||||
// via Schedule(CommandPtr&&). These are erased (destroyed) at the very end of
|
||||
// the loop cycle when the command lifecycle is complete.
|
||||
wpi::DenseMap<Command*, CommandPtr> ownedCommands;
|
||||
};
|
||||
|
||||
template <typename TMap, typename TKey>
|
||||
@@ -174,6 +179,12 @@ void CommandScheduler::Schedule(const CommandPtr& command) {
|
||||
Schedule(command.get());
|
||||
}
|
||||
|
||||
void CommandScheduler::Schedule(CommandPtr&& command) {
|
||||
auto ptr = command.get();
|
||||
m_impl->ownedCommands.try_emplace(ptr, std::move(command));
|
||||
Schedule(ptr);
|
||||
}
|
||||
|
||||
void CommandScheduler::Run() {
|
||||
if (m_impl->disabled) {
|
||||
return;
|
||||
@@ -226,6 +237,8 @@ void CommandScheduler::Run() {
|
||||
}
|
||||
|
||||
m_watchdog.AddEpoch(command->GetName() + ".End(false)");
|
||||
// remove owned commands after everything else is done
|
||||
m_impl->ownedCommands.erase(command);
|
||||
}
|
||||
}
|
||||
m_impl->inRunLoop = false;
|
||||
|
||||
Reference in New Issue
Block a user