📄 auto_ptr.cpp
字号:
// auto_ptr.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
struct X
{
X(const string& s):ss(s)
{
cout<<"X is constructed by "<<s<<endl;
}
~X()
{
cout<<"X is destructed by "<<ss<<endl;
}
void show()
{
cout<<"X shows : "<<ss<<endl;
}
private:
string ss;
};
typedef X XType ;
class auto_ptr
{
public:
auto_ptr():ptr(0){};
auto_ptr(XType* p);
auto_ptr(auto_ptr& a);
auto_ptr& operator=(auto_ptr& a);
virtual ~auto_ptr();
XType& operator*()const ;
XType* operator->()const ;
XType* get_ptr()const ;
private:
XType* ptr;
};
auto_ptr::auto_ptr(XType* p)
{
ptr=p;
}
auto_ptr::auto_ptr(auto_ptr& a)
{
ptr=a.ptr;
a.ptr=0; //为什么一定要将a.ptr赋值为0;
}
auto_ptr& auto_ptr::operator=(auto_ptr& a)
{
if(this==&a) return a; //防止自复制
ptr=a.ptr;
a.ptr=0;
return *this;
}
auto_ptr::~auto_ptr()
{
if(ptr!=0) delete ptr;
}
XType& auto_ptr::operator*()const
{
return *ptr;
}
XType* auto_ptr::operator->()const
{
return ptr;
}
XType* auto_ptr::get_ptr()const
{
return ptr;
}
int main(int argc, char* argv[])
{
X* p=new X("p");
auto_ptr ap(new X("ap")) ;
auto_ptr ap1=ap;
ap1->show();
(*ap1).show();
ap=ap1;
ap1->show();
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -