zoukankan      html  css  js  c++  java
  • String类的四个默认成员函数

    优化版的拷贝构造函数,先创建一个暂时实例tmp,接着把tmp._ptr和this->_ptr交换,因为tmp是一个局部变量。程序执行到该函数作用域外,就会自己主动调用析构函数。释放tmp._ptr所指向的内存。

    因为交换之后tmp._ptr指向实例之前_ptr的内存。_ptr一定要赋初值为NULL,否则析构一个随机值就会崩溃。我们在String的构造函数里用new分配内存,假设因为内存不足抛出诸如bad_alloc等异常。我们还没有改动原来的实例状态,保证了异常的安全性。

    #include<iostream>
    #include<string>
    #pragma warning (disable:4996)
    using namespace std;
    
    
    class String
    {
    public:
        String(char *p) :_ptr(new char[strlen(p) + 1])
        {
          if (_ptr != 0)
            {
                strcpy(_ptr, p);
            }
        }
        void swap(String &s)
        {
            char* tmp = s._ptr;
            s._ptr = _ptr;
            _ptr = tmp;
        }
        //优化版
        String(const String &s) :_ptr(NULL) //_ptr要置为NULL,否则释放一块随机值会出错
        {
            String tmp(s._ptr);
            swap(tmp);
        }
        /*String& operator= (const String &s)
        {
            if (this != &s)
            {
                String tmp(s._ptr);
                swap(tmp);
            }
            return *this;
        }*/
        //最优版
        String& operator= (String s)
        {
            swap(s);
            return *this;
        }
        //原始版本号
        /*String(const String &s)
        {
            _ptr = new char[strlen(s._ptr) + 1];
            if (_ptr != 0)
            {
                strcpy(_ptr, s._ptr);
            }
        }
        String& operator= (const String &s)
        {
            if (this != &s)
            {
                delete _ptr;
                _ptr = new char[strlen(s._ptr) + 1];
                if (_ptr != 0)
                {
                    strcpy(_ptr, s._ptr);
                }
            }
            return *this;
        }*/
    
    
        ~String()
        {
            if (_ptr)
            {
                delete[] _ptr;
            }
        }
        void Display()
        {
            cout << _ptr << endl;
        }
    private:
        char *_ptr;
    };
    
    int main()
    {
        String s1("yangrujing"), s2("yangfeipan");
        String s3(s1);
        s3.Display();
        s1 = s2;
        s1.Display();
    
        getchar();
        return 0;
    }
  • 相关阅读:
    zlog 使用手册
    Contribution and Coding Style Guide Bullet Physics Library
    Windows系统读写ext2/3/4文件系统的工具「ext2fsd」
    blender svn
    c# 各个版本
    c# Looping with the foreach statement
    C# 9.0 and .NET 5 – Modern Cross-Platform Development
    我的常用博客
    qml通过stacklayout实现页面切换
    JSON解析-android平台(转)
  • 原文地址:https://www.cnblogs.com/llguanli/p/8492702.html
Copyright © 2011-2022 走看看