zoukankan      html  css  js  c++  java
  • 关于智能指针

         读《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 }
  • 相关阅读:
    正则表达式的先行断言(lookahead)和后行断言(lookbehind)
    正则表达式里的捕获组
    JavaScript高级程序设计8.pdf
    JavaScript高级程序设计7.pdf
    JavaScript高级程序设计6.pdf
    JavaScript高级程序设计5.pdf
    JavaScript高级程序设计4.pdf
    产品思维|腾讯工作心得:原型该画到什么程度?
    提名推荐!15个2019年最佳CSS框架
    腾讯工作心得:原型该画到什么程度?
  • 原文地址:https://www.cnblogs.com/wanghetao/p/3085680.html
Copyright © 2011-2022 走看看