• 深拷贝的现代写法


    深拷贝的现代写法相比传统写法更加简单。也就是建立一个中间对象tmp,它的_str指针指向的内容是s._str的一份拷贝,交换tmp._str和_str后,_str就指向了s._str那份拷贝,出了作用域tmp会自动调用它的析构函数,也就把原先_str指向的内存释放了,同样达到了我们要的效果。

    如下图:

    #include<iostream>
    using namespace std;
     
    class String
    {
    public:
               String(char * str="")          //不能strlen(NULL)
                        :_str(new char [strlen(str ) + 1])
               {
                        strcpy(_str, str);
               }
               String(const String &s)
                        :_str(NULL )
               {
                        String tmp(s ._str);
                        swap(_str,tmp._str);
               }
               String& operator=(const String& s)
               {
                  if (this != &s)
                  {
                      String tmp(s._str);
                      swap(_str, tmp._str);
                  }
                  return *this;
               }
     
               ~String()
               {
                        delete[] _str;
               }
    private:
               char* _str;
    };
     
    

      当然,这里的赋值运算符重载还可以进行再优化:

     String& operator=(String s)  //优化 (s不能加引用,否则会改变实参的值)(这里的s是实参的一份拷贝)
               {
                        swap(_str, s._str);
                        return *this ;
               }
    

      

  • 相关阅读:
    websocket
    svg vs canvas
    nw
    web sql
    web worker
    【转载】磁盘阵列详解
    【识记】开源软件系列
    【转载】从1.5K到18K 一个程序员的5年成长之路
    SQL中in和not in
    SQL Server select count(distinct *)
  • 原文地址:https://www.cnblogs.com/Lynn-Zhang/p/5398842.html
Copyright © 2020-2023  润新知