当前位置:网站首页>Custom swap function

Custom swap function

2022-07-06 22:38:00 litanyuan

background

STL Provided in swap Algorithm , Used to exchange the values of two objects , The general implementation method is as follows :

namespace std{
    
    template<typename T>
    void swap( T&a,T&b )
{
    
        T temp(a);// Copy structure 
        a = b;// copy assignment 
        b = temp;// copy assignment 
    }
}

Resource management

①. summary

Usually contains resources ( The pointer ) The class of needs to provide a custom copy constructor and copy assignment operator .

②. Class definition

class demoClass
{
    
public:
    demoClass(const string& s = string()) :str(new string(s)) 
    {
     
        cout << " Constructor execution " << endl; 
    }
    demoClass(const demoClass& d):str(new string(*d.str))
    {
    
        cout << " The copy constructor executes " << endl;
    }
    demoClass& operator=(const demoClass& d)
    {
    
        cout << " Copy assignment function execution " << endl;

        auto newStr = new string(*d.str);// Copy the underlying resources 
        delete str;// Release old resources 
        str = newStr;// Assign new values to 
        return *this;
    }
    ~demoClass()
    {
     
        cout << " The destructor executes " << endl;

        delete str;  
    }

private:
    string* str;// The pointer 
};

③. Default swap operation

default swap The algorithm will execute the copy constructor once and the copy assignment operator twice , It will be more time-consuming for relatively large resources .

int main()
{
    
    demoClass d1 = demoClass("123");
    demoClass d2 = demoClass("456");

    cout << " perform  swap " << endl;
    swap(d1, d2);

    system("pause");
    return 0;
}

 Insert picture description here

④. Custom efficient swap

Corresponding to the class containing larger resources , When exchanging, you can exchange pointers directly . Put custom swap Function is defined as a friend function of a class to access private members .

class demoClass
{
    
public:
    friend void swap(demoClass& d1, demoClass& d2) noexcept;// Defined as friend 
   /*  ditto  */

private:
    string* str;// The pointer 
};

void swap(demoClass& d1, demoClass& d2) noexcept
{
    
    using std::swap;
    swap(d1.str, d2.str);// Exchange of pointer 
}

int main()
{
    
    demoClass d1 = demoClass("123");
    demoClass d2 = demoClass("456");

    cout << " perform  swap " << endl;
    swap(d1, d2);

    system("pause");
    return 0;
}

 Insert picture description here

 Insert picture description here

原网站

版权声明
本文为[litanyuan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061450383464.html