c++ - two different behavior in using default and overridden copy constructor -
when override copy constructor why segfaults in first delete itself. output:
$./a.out inside ctor inside copy-ctor in somefunc inside dtor *** glibc detected *** ./a.out: free(): invalid pointer: 0xb75f3000 *** if not override copy-ctor see s1.printval() getting called , there seg fault in *ptr expected.
why there 2 different behavior , without default , overridden copy-ctor?
#include<iostream> using namespace std; class sample { public: int *ptr; sample(int i) { cout << "inside ctor" << endl; ptr = new int(i); } sample(const sample &rhs) { cout << "inside copy-ctor" << endl; } ~sample() { cout << "inside dtor" << endl; delete ptr; } void printval() { cout <<" inside printval()."<<endl; cout << "the value " << *ptr<<endl; } }; void somefunc(sample x) { cout << "say in somefunc " << endl; } int main() { sample s1= 10; somefunc(s1); s1.printval(); return 0; }
in copy-ctor, don't copy ptr, meaning value unspecified, , you'll deleting unspecified pointer (instead of double-deleting normal pointer defauly copy-ctor).
Comments
Post a Comment