How do i dynamically allocate memory inside a class?
To clearify my question i made up an example. I would construct an instance a of A and copy it into b. After usage a and b would be destructed and the allocated memory would be freed twice in the destructor.
So how would i handle this situation?
#include <stdlib.h>
class A {
public:
char * allocatedMemory;
A(int length) {
allocatedMemory = (char *) malloc(sizeof(char) * length);
}
~A(){
free(allocatedMemory);
}
};
int main() {
A a = A(50);
A b = a;
return 0;
}
PS: To understand the Context: I am trying to figure out by example how std::string allocates and frees memory. Only the basic allocation of course.