Timeline for Accessing funcition in object via `->` is crashing (resetting) Arduino
Current License: CC BY-SA 4.0
9 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Jan 26, 2021 at 10:26 | comment | added | Majenko |
delete is to new what free is to malloc. You give it a pointer (as new provides a pointer) and it frees the object (calling the destructor) that pointer points to. With new, at no point do you ever "have" an object. You only ever have a pointer (with an associated type).
|
|
| Jan 26, 2021 at 1:08 | comment | added | Mike |
@Majenko I'm a very new to c++, and have a final follow up to your delete example. In your example, first you copy the pointer from the vector (same as: Base *myObj = myVector.back();. Then you wipe the element in the vector holding pointer (same as myVector.pop_back();). Finally you release the memory using the pointer. Am I correct? Also, when we delete myObj are we not deleting a pointer of Base type? shouldn't we be deleting the actual object, or this does delete the pointer AND the object? Sorry to pester you. I really appreciate your help!
|
|
| Jan 25, 2021 at 21:22 | comment | added | Majenko |
Base *ob = myVector[0]; myVector.erase(0); delete ob;
|
|
| Jan 25, 2021 at 21:19 | comment | added | Mike | @Majenko You ROCK!!! I don't know C++ at all and it's so hard to learn on the fly. Thanks a ton for your answer. Could I push my luck and please ask for an example on how to use the delete word? I'm totally new to C++ and really appreciate it. Could your example please assume C++99 is being used (if I'm lucky enough to get one)? | |
| Jan 25, 2021 at 20:59 | comment | added | Majenko | A C++11 shared_ptr smart pointer makes it easier, but no idea if ArduinoSTL supports them. | |
| Jan 25, 2021 at 20:58 | comment | added | PMF |
@Mike In your case, it's a bit complicated, because you have to do it when you remove elements or clear the myVector list. (Iterate over it with a for loop and delete all elements before you clear the vector). Using the STL (and some of the other features you use above) is quite advanced stuff for running on an Arduino, just because it's memory is very limited. You should probably look at some C++ tutorials first and run a few test programs on the PC first (where it's much easier to debug).
|
|
| Jan 25, 2021 at 20:53 | comment | added | PMF |
Note that std::vector<Base*> myVector; is a vector of pointers. You could store values in a vector as std::vector<Base> myVector;, but then you cannot store instances of derived classes.
|
|
| Jan 25, 2021 at 20:49 | vote | accept | Mike | ||
| Jan 25, 2021 at 20:01 | history | answered | Majenko | CC BY-SA 4.0 |