#include <memory>
#include <iostream>
using namespace std;
class MyClass
{
public:
int i;
MyClass(int s) {
i=s;
}
~MyClass() {
cout<<"This class has been destroied. "<<i<<endl;
}
void myFunc() {
cout<<"myFunc() done. "<<i<<endl;
}
};
int main()
{
auto_ptr<MyClass> ptr1(new MyClass(1));
auto_ptr<MyClass>ptr2(new MyClass(2));
ptr1->myFunc();
ptr2->myFunc();
cout<<"test 1 done\n"<<endl;
ptr2 = ptr1;
ptr2->myFunc();
//ptr1->myFunc();
cout<<"test 2 done\n"<<endl;
}
/*
$ ./a.out
myFunc() done. 1
myFunc() done. 2
test 1 done
This class has been destroied. 2
myFunc() done. 1
test 2 done
* */
如果上面ptr1->myFunc();
没有注释掉,那么结果如下。但我无法理解。我认为当时ptr1并没有被破坏......谁能帮助进一步解释一下?
$ ./a.out
myFunc() done. 1
myFunc() done. 2
test 1 done
This class has been destroied. 2
myFunc() done. 1
Segmentation fault (core dumped)