关于auto_ptr的疑问

林海 林海 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
#include "StdAfx.h"
#include "memory"
#include "string"
#include <iostream>
using namespace std;
int main()
{
auto_ptr<string> p1(new string("I'm p1"));
auto_ptr<string> p2(p1);
cout<<*p1<<":"<<(&p1)<<endl;
cout<<*p2<<":"<<(&p2)<<endl;
if (p1.get())
cout<<"p1 is full"<<endl;
if (p2.get())
cout<<"p2 is full"<<endl;
}

照理说auto_ptr<string> p2(p1)执行之后,p1应该属于未绑定,所以照理说应该不能够cout<<*p1,但是,程序确能够正常执行,很不解。而且get返回之后是非零值。


但是:
#include "StdAfx.h"
#include "memory"
#include "string"
#include <iostream>
using namespace std;

void f(auto_ptr<string> p)
{
cout<<"f: "<<*p<<endl;
}

int main()
{
auto_ptr<string> p1(new string("I'm p1"));
f(p1);
cout<<*p1<<":"<<(&p1)<<endl;
if (p1.get())
cout<<"p1 is full"<<endl;
}

程序执行之后报错,无法正常执行。这个大致理解,但是下面这样又不解了

#include "StdAfx.h"
#include "memory"
#include "string"
#include <iostream>
using namespace std;

void f(auto_ptr<string> p)
{
cout<<"f: "<<*p<<endl;
}

int main()
{
auto_ptr<string> p1(new string("I'm p1"));
auto_ptr<string> p2(p1);
f(p1);
cout<<*p1<<":"<<(&p1)<<endl;
cout<<*p2<<":"<<(&p2)<<endl;
if (p1.get())
cout<<"p1 is full"<<endl;
if (p2.get())
cout<<"p2 is full"<<endl;
}

又可以正常执行并显示结果,很不解。不是说复制或者赋值之后,原来的auto_ptr会重置为未绑定的auto_ptr对象么,但是我试验的结果却不是这样,求解释。
...全文
评论 10
收藏 已收藏
分享
返回顶部
林海
C++ 语言 65,214 成员 250,514 内容