I can’t seem to find any information on how the memory is managed for commands. The documentation instructs you to use commands as follows:
button2->WhenPressed(new Grab()); // In OI.cpp
SetDefaultCommand(new DriveWithJoysticksCommand()); // In subsystems
In C++ when you use the new keyword you are manually allocating memory to create that object and therefore must use the delete keyword to deallocate it when finished. My question is does the command scheduler automatically do this? If not how is that memory deallocated to prevent memory leaks from occurring?
We do our work in Java but from my understanding of how the structure works you actually reuse the instance of the commands, so you don’t actually need to worry about managing the memory for them. You’re not creating a whole bunch of commands over and over again.
Thanks for the reply. That makes sense. For some reason I was thinking that a new command was instantiated on every button press but I see now that’s not the case. Still curious about when/how that memory gets deallocated though.
Robots break some of the conventional rules here, as far as I can tell.
The intent is that the robot program never quit, which means you should never need to deallocate that memory. If you don’t need to deallocate the memory, you don’t need to go to the trouble of tracking the owner, hence the raw pointers. Owning raw pointers!? Sacrilege?
I checked the source code for Subsystem and didn’t find any evidence that it goes to the trouble of freeing m_defaultCommand at any point, even via the Scheduler. If you want to confirm, I recommend delving into the wpilib source. There’s always the possibility that I missed some RAII thing somewhere that’s handling the cleanup.
Assuming I am correct, it does mean that the slate needs to be wiped clean if the program crashes. Someone more informed about operating systems can probably explain how that works. I can only presume it does, in fact, work, considering teams use C++ successfully.
Yes, Linux automatically reclaims all memory used by a process when the process terminates. It’s not necessary for the program to do it. How this works at a low level is memory is allocated by the OS to the program as “pages” of (virtual) memory. The OS keeps track of this, and when the program terminates the OS reclaims the pages.