1: Create a pointer to 50 objects - then create each object on mouse click
in testApp.h
MyClass * objects[50];
int numObjects = 0;
in testApp.cpp
void testApp::setup(){
numObjects = 0;
}
void testApp::mousePressed(int x, int y, int button){
if(numObjects >= 50)return;
objects[numObjects] = new MyClass();
numObjects++;
}
//with pointers to objects you need to use -> instead of .
//so objects[i]->myFunction();
Or the c++ vector way. With a resizable c++ array.
in testApp.h
#include <vector>
vector <MyClass> objects;
int numObjects = 0;
in testApp.cpp
void testApp::setup(){
numObjects = 0;
}
void testApp::mousePressed(int x, int y, int button){
//add a new object to the end of our vector (c++ array)
//you can still reference each object like objects[i].myFunction();
objects.push_back( MyClass() );
numObjects = objects.size();
}
you’re actually deleting the whole array but not the objects, so you’ll end with all that memory lost. You have to loop the whole array position by position and delete each object. something like:
A general rule can be for each new you have in your code you must have a delete when you finish using that object.
For the second case, this same rule applies, you haven’t do a new for tmp, so if you do a delete you’re actually deleting obj1 or obj2.
Also usually you delete objects at the same level you created them, that way each function knows what it has created and what it has to delete.
re delete vs delete[]: when you go new[] (as opposed to just plain new) there’s a little bit of overhead allocated. delete[] will delete this overhead, plain delete won’t.
re ‘pointer being freed was not allocated’:
you’re allocating memory here:
px = new unsigned char[img.width*img.height*3]; // RGB
so px is a pointer to a fresh block of unsigned chars.
but then you overwrite px here:
px = img.getPixels();
so you’ve lost the pointer to your previously made fresh block - this is a memory leak - and you shouldn’t be trying to delete the pointer returned from img.getPixels().
Hi, quite an old thread, but gave me an idea of what I’m trying to achieve, is there a way to create the array of objects with smart pointers?
I was trying:
.h:
unique_ptr<Object>* objects[numObjects];
in cpp:
for (int i = 0; i < numObjects; ++i)
{
make_unique<Object>(x,y,z);
}
hello! std::make_unique (and often std::make_shared) are indeed the way to go as far as instantiation goes. so your idea close, you just need to hold onto the pointers somewhere as the objects are made.
std::array is the closest equivalence to a conventional array:
std::array<std::unique_ptr<Object>, numObjects> objects;
for (int i = 0; i < objects_array.size(); ++i) {
objects[i] = std::make_unique<Object>();
}
note that with the STL containers you can use this form to iterate:
// draw()
for (const auto & object: objects) {
object->do_your_draw_thing();
}
you could also use std::vector which is pretty convenient as it is dynamic (i.e. an array that can grow and shrink size over time).