I have the following code to test out my understanding of basic pointers in C++:
// Integer.cpp
#include \"Integer.h\"
Integer::Integer()
{
value = new int;
The problem you're experiencing is caused by the default copy constructor, which copies the pointer but doesn't associate it with newly allocated memory (like your implementation of copy constructor does). When you pass object by value, a copy is created and when the execution goes out of scope, this copy is destructed. delete
from the destructor invalidates the value
pointer of intVal1
object, making it dangling pointer, dereferencing of which causes undefined behavior.
Debug outputs might be used to understand the behavior of your code:
class Integer {
public:
Integer() {
cout << "ctor" << endl;
value = new int;
*value = 0;
}
~Integer() {
cout << "destructor" << endl;
delete value;
}
Integer(int intVal) {
cout << "ctor(int)" << endl;
value = new int;
*value = intVal;
}
Integer(const Integer &rhInt) {
cout << "copy ctor" << endl;
value = new int;
*value = *rhInt.value;
}
Integer& operator=(const Integer& rhInt){
cout << "assignment" << endl;
*value = *rhInt.value;
return *this;
}
int *value;
};
void foo(Integer intObj) {
cout << intObj.value << " " << *(intObj.value) << endl;
}
Now output of this code:
Integer intVal1;
Integer intVal2(10);
foo( intVal1 );
foo( intVal2 );
intVal1 = intVal2;
foo( intVal1 );
is:
ctor
ctor(int)
copy ctor
0x9ed4028 0
destructor
copy ctor
0x9ed4038 10
destructor
assignment
copy ctor
0x9ed4048 10
destructor
destructor
destructor
which shows that copy constructor is used when passing objects by value. However, important to notice here is the destructor called upon the return from your function. And if you remove your implementation of copy constructor, then the output is:
ctor
ctor(int)
0x8134008 0
destructor
0x8134018 10
destructor
assignment
0x8134008 135479296
destructor
destructor
destructor
showing that the first copy called delete
on the same pointer (pointing to 0x8134008
) as was used by third copy later, where the memory pointed by this dangling pointer has been used.