I'm a bit confused w.r.t. the usage of delete and creation of new objects. Say I have a class which stores pointers to some other object in an array:
#include <array>
#include "someObject.hpp"
class someContainer() {
std::array<someObject*, 10> objects;
void set_object(int n);
}
What is the best way to create and store instances of someObject in the set_object function that does not involve the usage of smart pointers or other wrappers.
For example, I believe that...
void someContainer::set_object(n) {
// Some check that 0 < n < 9
...
//=====
someObject object* = &someObject(constructor_param);
objects[n] = object;
}
... will result in undefined behavior, because the destructor of object's reference is called upon the function's exit.
Would the correct way, then, be this?
void someContainer::set_object(n) {
// Some check that 0 < n < 9
...
//=====
someObject object* = new someObject(constructor_param);
objects[n] = object;
}
void someContainer::~someContainer() {
int len = objects.size
for (int i=0; i < len; i++) {
delete objects[i];
}
Or is there undefined behavior somewhere that I'm missing? (Also, I think that one shouldn't iterate through the array while also deleting objects from it, which is why I use the len index. Is this true?) I'm asking here because things compile and seem to work well, but I'm having a hard time really knowing.