Hello everybody. I face a weird problem. I have a vector of objects that I sort using the sort() and a predicate function. When in the class of the object I include a copy constructor, after the sorting the values of the objects in the vector are corrupted.
Can you please help me understand why this is happening?
Bellow is the code:
1 2 3 4 5 6 7 8
class Node {
public:
int degree;
Node();
Node(const Node& orig);//when I comment it out I have no problem
};
1 2 3 4 5 6 7 8 9
vector<Node> myVec;
//Populate the vector
for (int i=0; i<10; i++){
Node a_node;
a_node.degree = i;
myVec.push_back(a_node);
}
sort(nodes.begin(), nodes.end(), myPredicate);
Degree of 1 = 1
Degree of 2 = 2280200
Degree of 3 = 2280200
Degree of 4 = 2280200
Degree of 5 = 2280200
Degree of 6 = 2280200
Degree of 7 = 2280200
Degree of 8 = 2280200
Degree of 9 = 2280200
Degree of 10 = 2280200
The copy ctor is auto generated by the compiler UNLESS you define it yourself.
You are defining it yourself (and having it not do anything), therefore the compiler doesn't generate a new one for you. Therefore the object is being improperly copied when vector moves it around (it, in fact, is not being copied at all because your copy ctor does nothing).
The moral of the story here is don't have empty copy ctors.