vector of objects corrupted when sorting

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);


1
2
3
bool myPredicate(const Node &n1, const Node &n2){
    return n1.degree < n2.degree;
}


With the copy constructor defined I get


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


while without it I get the correct sorted output.

Thank you!
Well your copy constructor is obviously wrong.

Can you post it for us so we can see? Is it even necessary to write your own copy ctor for this class? (it doesn't look like it)
It is auto-generated from the compiler. In the corresponding cpp file (Node.cpp) both constructors' bodies are empty.

1
2
3
4
5
Node::Node(){
}

Node::Node(const Node& orig) {
}
Last edited on
Ah okay.

You're misunderstanding.

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.

Or

Don't write a copy ctor unless it's necessary.
Thank you for the answer
The same answer is true for the assignment operator.
closed account (1yR4jE8b)
Unless you are using dynamic memory allocation in your class you do not need:

1.Copy Constructor
2.Destructor
3. Assignment Operator

The compiler generated ones will suit just fine, so don't even bother to define them.
Topic archived. No new replies allowed.