// fowl.cpp -- auto_ptr a poor choice
#include <iostream>
#include <string>
#include <memory>
int main()
{
using namespace std;
auto_ptr<string> films[5] =
{
auto_ptr<string> (new string("Fowl Balls")),
auto_ptr<string> (new string("Duck Walks")),
auto_ptr<string> (new string("Chicken Runs")),
auto_ptr<string> (new string("Turkey Errors")),
auto_ptr<string> (new string("Goose Eggs"))
};
auto_ptr<string> pwin;
pwin = films[2]; // films[2] loses ownership
cout << "The nominees for best avian baseball film are\n";
for (int i = 0; i < 5; i++)
cout << *films[i] << endl;
cout << "The winner is " << *pwin << "!\n";
// cin.get();
return 0;
}
上述代码在*films[2]处会直接闪退,因为pwin = films[2]后,film[2]就是nullptr了
上述代码把auto_ptr改为shared_ptr,程序正常运行,其原理为shared_ptr的采用引用计数策略,在pwin声明时,shared_ptr内部实现了+1,等程序结束前,先调用pwin的析构,计数-1,然后调用film[2]的析构-1并执行detele空间
上述代码把auto_ptr改为unique_ptr,编译器报错,其原理如果时临时右值,则允许赋值