I find myself so frequently thoughtlessly writing classes that add pointers to objects which are later destroyed to lists, which results in a lot of segfaults, but the problem is that sometimes I simply can't come up with a better solution than to store a list of pointers. It does my head in that there doesn't seem to be a simple way of just "storing temporary objects that you can't copy" in C++. Is there a paradigm I'm missing on how to do this effectively?
For example, I'll have a class that looks something like this:
class MyClass
public:
std::vector<OtherClass *> other_objects;
void method() {
OtherObject other_object = create_other_object();
other_objects.push_back(&other_object);
}
One reason you may want to do this is because you use the other_objects
elsewhere (as arguments to other functions) and you can't copy OtherObject
instances (which could happen if the OtherObject
copy constructor was private for example).
Of course, once you attempt to use other_objects
elsewhere in code, the memory each pointer points to will have already been destroyed.
I write a lot of Python code, and I use this sort of structure very often, where a method populates an iterable with objects that exist solely in the scope of the method. Is there a way to do this effectively in C++? Could I do my own memory management to keep the temporary objects in the method alive beyond the scope of the method?