读《C++ Stragegies and Tacitics》的时候看到了一段很NB的代码,是关于智能指针的 (程序稍作修改,以便在编译器上运行):

 1 #include <string>
 2 using namespace std;
 3 
 4 class String_ptr {
 5 private:
 6     string *ptr;
 7 public:
 8     String_ptr(string *s) : ptr(s) {}
 9     string* operator ->() const {return ptr;}
10     operator string*() const {return ptr;}
11 };
12 
13 int main(){
14     string s("hello world!");
15     String_ptr sp=&s;
16     int len=sp->length();         //(sp.operator ->())->length();
17     string *dumb_ptr = sp;      // sp.operator string *();
18 }

     类String_ptr是一个只能指针,用来控制对其所负责的string的访问。其中定义了两个函数 operator->()(用来对string成员函数的访问)和operator string*()(用来进行隐式类型转换的函数)。

     我最大的疑问就是为什么operator string*()函数没有返回值(返回值应该为 string *)?如果函数声明改写为:

string* operator string *() const ;

     重新编译就会出错 error: return type specified for 'operator std::string* {aka std::basic_string<char>*}。原来在operator std::string* ()声明中就已经指定了返回值类型。

     注意sp的初始化也很不一般:“String_ptr sp=&s;”调用的是String_ptr的构造函数,而不是复制构造函数。

 

     使用模板来实现该智能指针:

 

 1 #include <string>
 2 using namespace std;
 3 
 4 template <class T>
 5 class Ptr {
 6 private:
 7     T* ptr;
 8 public:
 9     Ptr(T* p) : ptr(p) { }
10     T* operator ->() const {return ptr;}
11     operator T*() const {return ptr;}
12 };
13 
14 int main(){
15     string s("hello world!");
16     Ptr<string> sp=&s;
17     int len=sp->length();
18     string *dumb_ptr=sp;          //sp.operator string *();
19 }

 

 

 

posted on 2013-05-18 17:14  wanghetao  阅读(384)  评论(0编辑  收藏  举报