c++的auto_ptr
·
auto_ptr的指针在使用=赋值时,遵循的是transfer ownershiptransfer\ ownershiptransfer ownership原则,即,只有一个指针才可以对对象有拥有权。
实例
#include<iostream>
#include<string>
#include<memory>
int main()
{
using namespace std;
auto_ptr<string> films[5] =
{
auto_ptr<string> (new string("hablee")),
auto_ptr<string> (new string("yuki")),
auto_ptr<string> (new string("goose")),
auto_ptr<string> (new string("turkey")),
auto_ptr<string> (new string("duck"))
};
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;
}
第17行经过赋值运算符之后,films[2]的指针已经失去了对flims[2]对象的拥有权,因此,后面在循环输出flims[2]指向的内容时,会发生异常,中断程序输出
结果
the nominees for best avian baseball film are
hablee
yuki
E:\projectFiles\CPPcodes\learn_cpp\SmartPointer002\x64\Release\SmartPointer002.exe (进程 52516)已退出,代码为 -1073741819。
按任意键关闭此窗口. . .
参考文献
c++ primer plus (6 edition, English edition)
更多推荐
所有评论(0)