As the title says I'm putting pointers to objects in a vector. The way I'm doing it right now is like follows: (object 1, 2 and 3 are all derived from the same class Object)
As I create more and more objects this will get really tedious so I'm wondering is there a more efficient way to do this? Maybe some way that you could create the object and pointer at the same time? (maybe even assign it at the same time?). One can assume that I'll know how many objects and pointer I'll need in advance.
FYI, the way you are doing that could be bad if your objects go out of scope before the vector does:
1 2 3 4 5 6
vector<Object*> objs;
{
Object myobj;
objs.push_back(&myobj);
}
objs[0]->oh_crap(); //<-- bad! objs[0] points to garbage because myobj is not alive anymore
Using heap memory easier, but you have to remember to delete the objects:
And then you can use boost::ptr_vector<>, which is the same thing as std::vector<> except
it works only for pointers, and takes care to delete the pointer when the element is removed
so you avoid the memory leak firedraco mentioned.
wouldn't this make a new Object and not an Object* ? How would I go about if I wanted to do something like that but with pointers?
In my case I have three classes; Shape, Shape2D and Triangle (for now). Shape2D is derived from shape and Triangle is derived from Shape2D. The classes has a member function menu() in common (and some more) what I'm trying to do is something like this:
Is this correct? Is the dynamically created objects deleted and no memory leaks?
I find this delete and new to be very abstract for some reason, when I use delete (or rather when it's executed) this is when the object's destructor is called? And if I don't use delete the memory this object (created by 'new') occupy will not be returned until the program is fully executed?
Think of a pointer as just another variable that happens to contain a value that
magically "points to" another variable.
Your code above is completely correct with no memory leaks.
If you are familiar with malloc and free, then you can think of "new" as "malloc +
runs the constructor" and "delete" as "free + runs the destructor".
For modern OSes that understand virtual memory, if you don't release the memory
the kernel will release it upon program exit. For older OSes such as DOS, if you
forget to release memory, then the memory remains allocated even after the
program exits.
That is a good way of thinking about it, I feel. (Still probably need to read about it a little more though). Thank you for that explanation and all the help jsmith (and firedraco too of course)!