C++编程调试秘笈----读书笔记(三)
*students2;
students2 = smartPoint3->Release(); //释放smartpoint保存原来的地址
students2->ShowAge();
return 0;
}
综合两个smart point的例子,使用方式都是“每次使用new操作符创建一个对象时,立即把结果赋值给一个智能指针”。
以上的两个smart point其实都没解决一个问题,就是当我们的对象是const的情况,怎么办?分析一下这种情况,传入smart point的对象是一个const,这以为这里面的一些成员变量是无法修改的,所以有了下面的一种半智能的smart point:
scpp_ptr.h:
[cpp]
#ifndef __SCCP_PTR_H__
#define __SCCP_PTR_H__
#include "scpp_assert.h"
namespace scpp
{
template
class Ptr
{
public:
explicit Ptr(T *p = NULL)
: ptr_(p)
{
}
T* Get() const
{
return ptr_;
}
Ptr& operator = (T *p)
{
ptr_ = p;
return *this;
}
T& operator * () const
{
SCPP_TEST_ASSERT(ptr_ != NULL, "Attempt to use operator -> on NULL pointer.");
return *ptr_;
}
T* operator -> () const
{
SCPP_TEST_ASSERT(ptr_ != NULL, "Attempt to use operator -> on NULL pointer.");
return ptr_;
}
~Ptr()
{
}
private:
T* ptr_;
};
} // namespace scpp
#endif // __SCCP_REFCOUNTPTR_H__
测试代码(vs2012+win7环境):
[cpp]
#include "stdafx.h"
#include "scpp_assert.h"
#include "iostream"
#include "scpp_vector.h"
#include "scpp_array.h"
#include "scpp_matrix.h"
#include "algorithm"
#include "scpp_types.h"
#include "scpp_refcountptr.h"
#include "scpp_scopedptr.h"
#include "scpp_ptr.h"
#define STUDENTAGE 10
class Student
{
public:
Student(int age) : age_(age)
{
}
void ShowAge()
{
std::cout << "my age is : " << age_ << std::endl;
}
int GetAge() const
{
return age_;
}
void SetAge(int age)
{
age_ = age;
}
private:
int age_;
};
int _tmain(int argc, _TCHAR* argv[])
{
Student *student1 = new Student(STUDENTAGE); //@test:operator -> (T *p)
scpp::Ptr smartPoint1;
smartPoint1 = student1;
smartPoint1->ShowAge();
Student *student2 = new Student(STUDENTAGE); //@test:operator * (T *p)
scpp::Ptr smartPoint2;
smartPoint2 = student2;
(*smartPoint2).ShowAge();
Student *student3 = new Student(STUDENTAGE); //@test:operator * (T *p)
scpp::Ptr smartPoint3;
smartPoint3 = student3;
std::cout << "this student age is : " << smartPoint3->GetAge() << std::endl;
smartPoint3->SetAge(STUDENTAGE); //@因为被限制,所以无法使用,也没必要使用
return 0;
}