Part of the task I have is to create a class, which contains two lists of two other classes and create “The big 4″(constructor, copy constructor, operator=, destructor)
Here’s what I did:
using namespace std;
class A{...};
class B{...};
class C{
list<A> a;
list<B> b;
public:
C();
~C();
C(const C& c);
void operator=(const C& c);
};
C::C(){
//How to allocate memory for a and b?
}
C::~C(){
//How to free the memory?
}
C::C(const C& c){
a=c.a;
b=c.b;
}
void operator=(const C& c){
if(&c==this) return;
// how do I delete a and b?
a=c.a;
b=c.b;
}
Could you clear out the things that I don’t understand(as comments in the code). And also give advice if I haven’t done anything correctly?
Since you’re using values (
std::listvalues), there is nothing to do. Your constructor will call thestd::listconstructors automatically, which allocate any resources needed. Your destructor will call thestd::listdestructor, which frees resources which it acquired.You would need some extra work if you either hold pointers to lists (i.e.
std::list<A> *a;) or lists of pointers (std::list<A*> a;') – or both (std::list<A*> *a;).