Since you're dynamically allocating the data members texData
and texCoords
you'll need to follow the Rule of Three, and define a copy constructor and copy assignment operator too, or your code will be very easily broken, as you've discovered.
But there's a better way! Do no use raw pointers as data members. Use unique_ptr
s to hold them. (It's possible you don't need them to be pointers at all, but I'll give you the benefit of the doubt here). You'll still need to define a copy constructor and copy assignment operator, and manually copy the contents of what the unique_ptr
s are holding, if you want the class to be copyable.
And to make it moveable you can explicitly =default
both the move contructor and move assignment operators.
Also, your code is leaking memory. You allocate those objects dynamically, and then push_back
a copy into the vector
Texture * a = new Texture();
buttons.push_back(*a);
You're dereferencing a
and adding a copy of it to the vector
. Unless you delete a;
before it goes out of scope, you've got a memory leak. Use a vector<unique_ptr<Texture>>
instead.
vector<unique_ptr<Texture>> buttons;
buttons.push_back(unique_ptr<Texture>(new Texture()));
With C++14 you can use make_unique
to avoid having to new
the object yourself
buttons.push_back(make_unique<Texture>());
Additionally, if you know the number of buttons you're going to add in advance you can reserve
space to avoid reallocations.
buttons.reserve(num_buttons);
Now, chances are you do not actually need to dynamically allocate the Texture
objects at all. All you probably need is
vector<Texture> buttons;
buttons.push_back(Texture());
If possible, I'd also define a move contructor and move assignment operator for Texture
so that it can be moved when the vector reallocates, instead of being copied.