Defining Smart Pointer Classes(スマートポインタ)
2183 ワード
/*
* HasPtr.h
*
* Created on: 2014-10-25
* Author: Thinkpad
*/
#ifndef HASPTR_H_
#define HASPTR_H_
#include "U_ptr.h"
using namespace std;
class HasPtr {
public:
HasPtr();
virtual ~HasPtr();
HasPtr(int *p, int i) :
ptr(new U_ptr(p)), val(i) {
}
HasPtr(const HasPtr &orig) :
ptr(orig.ptr), val(orig.val) {
++ptr->use;
}
int getVal(){
return val;
}
HasPtr& operator=(const HasPtr&);
private:
U_ptr *ptr;
int val;
};
#endif /* HASPTR_H_ */
/*
* HasPtr.cpp
*
* Created on: 2014-10-25
* Author: Thinkpad
*/
#include "HasPtr.h"
using namespace std;
HasPtr::HasPtr() {
// TODO Auto-generated constructor stub
}
HasPtr::~HasPtr() {
if(--ptr->use == 0){
delete ptr;
}
}
HasPtr& HasPtr::operator=(const HasPtr& rhs){
++rhs.ptr -> use;
if(--ptr->use == 0){
delete ptr;
}
ptr = rhs.ptr;
val = rhs.val;
return *this;
}
/*
* U_ptr.h
*
* Created on: 2014-10-25
* Author: Thinkpad
*/
#ifndef U_PTR_H_
#define U_PTR_H_
using namespace std;
class U_ptr {
public:
friend class HasPtr;
int *ip;
int use;
U_ptr();
U_ptr(int *p,int use): ip(p),use(use){};
U_ptr(int *ip);
virtual ~U_ptr();
};
#endif /* U_PTR_H_ */
/*
* U_ptr.cpp
*
* Created on: 2014-10-25
* Author: Thinkpad
*/
#include "U_ptr.h"
U_ptr::U_ptr() {
// TODO Auto-generated constructor stub
}
U_ptr::U_ptr(int *ip): ip(ip),use(1) {
this->ip = ip;
}
U_ptr::~U_ptr() {
delete ip;
}
/*
* main.cc
*
* Created on: 2014-10-25
* Author: Thinkpad
*/
#include <iostream>
#include <string>
#include "HasPtr.h"
using namespace std;
void testSmartPointer(){
int i = 42;
HasPtr p1(&i,i);
HasPtr p2(p1);
HasPtr p3(p2);
cout << p1.getVal() << endl;
cout << p2.getVal() << endl;
cout << p3.getVal() << endl;
}
void wait_a_moment(){
string wait;
cin >> wait;
}
int main(){
testSmartPointer();
}
説明:……