lundi 25 mai 2015

Shall I build a destructor in this classes?

I am currently working on building an ABM model using C++.

I have classes that have the need to interact with each other, because e.g. class B needs to examine values in class A and return some evaluation on it, which then class C might want to read. Classes need not to change other classes values, only to read from them.

Class B in my current implementation has a po inter to a vector containing all members of Class A. The pointer is there for two order of reason: it makes easier to initialize the vector, and the vector is left in the scope of main so that I can access and loop over it, calling the members of class A for each agent.

My MCVE:

#include <iostream> 
#include <vector>

using namespace std;

class A;    // Forward declaration

class B{


int id,
    some_value;

vector<A> * A_vec;

public:

// Overloaded constructor
B(int ID, vector<A> & PTR)
{   
A_vec = & PTR;
id = ID;
some_value = 0;
};
// Copy Constructor

B( const B& that ):
id(that.id),
some_value(that.some_value)
{
// Pointer ??
};

// Non-default destructor -> uncomment leads to seg_fault
/*
~B(){   delete [] A_vec;};
*/
// Assignment operator

B& operator=(const B& that)
{
id = that.id;
some_value = that.some_value;
// Pointer ??
return *this;
};
//Copy Constructor


//Methods to update different variables go here ..
void do_stuff();

};



class A{

    B & class2_ref;
    vector<double> o;


public:

int stuff;

// Overloaded constructor

A(int STUFF, B & REF, vector<double> O):

class2_ref(REF),
o(O)

{
stuff = STUFF;  
};

// Methods to update different variables go here ..



};  

void B::do_stuff()
{
    int L = A_vec->size();  
    for(int l = 0; l<L; l++)  some_value += (*A_vec)[l].stuff; // Perform some operation

};


int main(){

int I = 5;          // Number of objects of A

vector<A> A_vec;

B b(0,A_vec);

vector<double> O(12,2); // Some numbers in here

for(int i = 0; i< I; i++){
A a(i,b,O);
A_vec.push_back(a);
}

b.do_stuff();

cout<< "Debugging MCVE" << endl;
return 0;

}

My question then is:

Should I implement the destructor/copy constructor/assignment operator in class B? What about class A ? If so, can you please point me to the correct syntax(for the destructor the one above in comments leads to seg fault).

My understanding is that this might be one of the case in which I am happy with a "shallow" destruction of the pointer, because both class B and vector<A> will go out of scope at the return statement. class B owns the pointer, which gets destructed when it is due, and the same for vector.

But then, what about the other member from the rule of three?

There is only one object of class B planned, but I might (small chance) want to generalize later on.

Aucun commentaire:

Enregistrer un commentaire