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 }
  • 相关阅读:
    USACO 2019 January Contest Platinum T2: Exercise Route
    USACO 2016 December Contest Gold T3: Lasers and Mirrors
    USACO 2016 December Contest Gold T2: Cow Checklist
    USACO 2016 December Contest Gold T1: Moocast
    USACO 2016 US Open Contest Gold T3: 248
    洛谷p5369[PKUSC2018]最大前缀和
    洛谷p5465 [PKUSC2018]星际穿越
    洛谷p3778[APIO2017]商旅
    NOIP2018提高组题解
    NOIP2017提高组题解
  • 原文地址:https://www.cnblogs.com/wanghetao/p/3085680.html
Copyright © 2011-2022 走看看