auto_ptr

chinaplus 2007-01-08 10:28:04
auto_ptr have an unusual characteristic: copying them(via copy constructor or copy assignment)sets them to null.

why the program run correctly:
#include <stdAfx.h>
#include <iostream>
#include <memory>
using namespace std;

class A
{
public:
A(int a):m_iData(a){};
void print(){cout<<this->m_iData<<endl;}
private:
int m_iData;
};

void smart()
{
auto_ptr<A> m_pSmartA(new A(2));
//m_pSmartA->print();
auto_ptr<A> m_pSmartA1(m_pSmartA);
m_pSmartA1->print();
m_pSmartA->print();
};

void main()
{
smart();
}

the result:
2
2
i was puzzled how the result got.
can u tell me why? thank u first.
...全文
192 16 打赏 收藏 转发到动态 举报
写回复
用AI写文章
16 条回复
切换为时间正序
请发表友善的回复…
发表回复
chinaplus 2007-01-08
  • 打赏
  • 举报
回复
谢谢大家了!呵呵
chinaplus 2007-01-08
  • 打赏
  • 举报
回复
那在vc6.0中可以用STL库吗,呵呵,不好意思,我还没有用过STL
todototry 2007-01-08
  • 打赏
  • 举报
回复
赞自个
todototry 2007-01-08
  • 打赏
  • 举报
回复
真整齐
todototry 2007-01-08
  • 打赏
  • 举报
回复
对于0指针进行解引用,行为属未定义
对于0指针进行delete,是安全的行为
zhousqy 2007-01-08
  • 打赏
  • 举报
回复
汗,想起來了:(
晨星 2007-01-08
  • 打赏
  • 举报
回复
要么学习标准C++,要么用VC6,两者是不可兼得的,嘿嘿。

当然,这不能怪微软,因为VC6发布的时候,C++标准化工作还没完成。而C++标准化工作完成之后,人家微软还是出了更好的新版本的,比如VC7.0,2003,2005等。
a_b_c_abc9 2007-01-08
  • 打赏
  • 举报
回复
auto_ptr 的特征是所有权转移,也就是任何时候只会有一个auto_ptr 对象指向你的对象.

void smart()
{
auto_ptr<A> m_pSmartA(new A(2));
m_pSmartA->print();
auto_ptr<A> m_pSmartA1(m_pSmartA);//这里,用pSmartA构造pSmartA1时,发生了所有权转移.m_pSmartA不再指向(new A(2)),而是由m_pSmartA1指向(new A(2))
m_pSmartA1->print();
m_pSmartA->print();//所以这里是用一个无效的对象在调用,相当C中NULL指针调用.
};
taodm 2007-01-08
  • 打赏
  • 举报
回复
你打开vc6的memory这个头文件,看一下它的实现就知道原因了。
chinaplus 2007-01-08
  • 打赏
  • 举报
回复
呵呵,先谢谢大家了.
void smart()
{
auto_ptr<A> m_pSmartA(new A(2));
//m_pSmartA->print();
auto_ptr<A> m_pSmartA1(m_pSmartA);
m_pSmartA1->print();
m_pSmartA->print();
};

auto_ptr<A> m_pSmartA1(m_pSmartA);
运行这条语句后,m_pSmartA应该为NULL,
如果继续运行m_pSmartA->print()就会报错啊,
但是我在VC6.0中运行是正确的啊.
taodm 2007-01-08
  • 打赏
  • 举报
回复
楼主用的VC6吧,扔了,换devcpp
晨星 2007-01-08
  • 打赏
  • 举报
回复
用g++3.4.4也一样。- -b
楼主用的是啥编译器啊?竟能正常运行?
晨星 2007-01-08
  • 打赏
  • 举报
回复
“程序”,打错了。
晨星 2007-01-08
  • 打赏
  • 举报
回复
偶用VC2003编译运行楼主的程度,引发严重的运行时错误。- -b
zhousqy 2007-01-08
  • 打赏
  • 举报
回复
new了一個A的object,用pSmartA和pSmartA1分別指向那個object
todototry 2007-01-08
  • 打赏
  • 举报
回复
auto_ptr<A> m_pSmartA1(m_pSmartA);
此时m_pSmartA指向null了,释放对象A(2)的所有权

64,642

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧