The following code gives an exception for g++ version 4.6.2, but runs as expected with g++ version 4.2.1. Messages printed during execution indicate that in both cases a destructor is being called on an address which was never constructed. I would like to know (a) which of the compilers is correct, (b) why is something being destroyed without being created. Thanks much.
//------------------------------------------------------
#include <iostream>
using namespace std;
class Poly{
private:
float *coeff;
public:
Poly(){
coeff = NULL;
cout << "Created "<< this << endl;
}
Poly(Poly const & p){ // copy constructor
coeff = NULL;
cout << "Executed copy constructor.\n";
}
Poly operator=(Poly const & rhs){
cout << "Executed assignment. " << this << " = " << &rhs << endl;
}
Poly fun(){
Poly c;
return c;
}
~Poly(){
cout << "Destructor: " << this << endl;
delete[] coeff;
}
};
main(){
Poly a;
a = a.fun();
}
//------------------------------------------------------
For g++ 4.6.2 it gives and exception:
% ./a.out
Created 0xbfdcc184
Created 0xbfdcc18c
Executed assignment. 0xbfdcc184 = 0xbfdcc18c
Destructor: 0xbfdcc188
*** glibc detected *** free(): invalid pointer: 0xbfdcc1a8 ***
Aborted
For g++ 4.2.1 it does the following
% ./a.out
Created 0x7fff5fbff930
Created 0x7fff5fbff920
Executed assignment. 0x7fff5fbff930 = 0x7fff5fbff920
Destructor: 0x7fff5fbff910
Destructor: 0x7fff5fbff920
Destructor: 0x7fff5fbff930
There is no exception, and with more code it does produce the correct answer. However, it does seem to be destroying 0x7fff5bff910 which never was constructed. Note that the copy constructor is never called, it would print a message if it had been.
It looks like your "Poly operator=" does not return anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With