If I have an Element vector and I want to set field 'data' with dynamic memory (I want to create a new object each time a function is called), how do I do it?
// Example program
#include <vector>
#include <string>
using std::string;
using std::vector;
class myClass;
struct Element {
string name;
myClass *data;
};
class myClass {
};
int main()
{
vector<Element> elements;
elements.push_back( { "my_name", new myClass() } );
delete elements[0].data; // cleanup
}
it is generally bad practice to put a pointer in a class and manage the memory yourself. but you asked, and this is how you do it.
- either the constructor allocates the memory with new, or it sets the member to null.
- if the constructor sets to null, then a setter function will allocate the memory. The setter function will check null, and if not null, you have a choice of delete and re-allocate or ignore the call to setter (its already been called).
- the destructor will call delete.
- you need to ensure your class will function with rules of 3/5.
this is a LOT of bloat, a lot of things to screw up, more things to test, and so on. Its terrible.