Hi I have the following code (shown below) which is a class brt_node with 3 members, one of them being an static array called "buffer", the elements of this buffer are pairs (int, CDataType), the CDataType is also shown.
I have created my own copy constructors and assignment operators, so that when I do something like the in following lines, I don't have to copy all the buffer, but only the part I am interested in, and given by the function get_buffer_size()
Code:
brt_node x;
//... do something with x
brt_node n = x; // copy constructor
brt_node y;
y = n; // assignment operator
I know that executing the lines above will work (without my own copy constructor and assigment operator), c++ takes care of it, but is very slow (I don't need to have the whole buffer copied);
The copy constructor and assigment operator I have defined, do not seem to work properly (segmentation fault sometimes);
Btw, the array has to be static, don't want a dynamic array in this specific case.
I would appreciate some help fixing it. Thanks in advance.
Code:
class CDataType{
public:
// constructors:
CDataType():
vertex(0),
number(0){}
CDataType(const unsigned int &_v, const cases &_status = unexplored, const unsigned int &_number = 0):
vertex(_v),
number(_number){}
const CDataType &operator=(const CDataType &e) {
if ( &e != this){
this->vertex = e.vertex;
this->number = e.number;
return (*this);
}
}
// -- attributes
unsigned int vertex;
unsigned int number;
};
// -- type of each record stored in the brt_node's buffer
typedef std::pair<unsigned int, CDataType> value_type;
class brt_node {
public:
// constructors
brt_node():
left(0), two_children(false)
{ buffer[0] = value_type(0, CDataType(0) ); };
brt_node(const value_type &_key_pair):
left(0), two_children(false)
{ buffer[0] = _key_pair; }
brt_node(const unsigned &_key):
left(0), two_children(false)
{ buffer[0] = value_type(_key, CDataType(0) ); }
// copy constructor
brt_node(const brt_node &_n):
left(_n.get_leftChildPos()),
two_children(_n.has_2_children())
{ std::copy(_n.buffer, _n.buffer+_n.get_buffer_size()+1,buffer); }
// functions
KeyType get_key() const { return buffer[0].first; }
void set_key(const KeyType &_key) { buffer[0] = value_type(_key, CDataType(0)); }
KeyType get_buffer_size() const { return buffer[0].second.vertex; }
void set_buffer_size(const unsigned int &size) { buffer[0].second.vertex = size; }
bool has_2_children() const { return two_children; }
void set_has_2_children(const bool &_two_children) { two_children = _two_children; }
unsigned int get_leftChildPos() const { return left; }
void set_leftChildPos(const unsigned &_index) { left = _index; }
// -- object assignment operator
const brt_node &operator=(const brt_node &n) {
if ( &n != this){
left = n.get_leftChildPos();
two_children = n.has_2_children();
std::copy(n.buffer, n.buffer+n.get_buffer_size()+1, buffer);
return (*this);
}
}
value_type buffer[BUFFER_SIZE];
private:
unsigned int left;
bool two_children;
};