25. Write out a swap function without throwing an exception-Objective C ++ Study Notes

Source: Internet
Author: User

STD: swap is a template that provides a replacement operation that swaps the internal values of A and B of the same type. Swap operations require that objects support copying constructor and copying assignment function. In internal operations, three assignment objects are used.

There is a problem here, that is, for a specific object, its efficiency will be very low. Therefore, we need to make a special swap for a specific object.

Summary:

1,
If swap's default implementation code provides acceptable efficiency for your class or class template, you do not need to do anything else ,.

2,
If swap's default implementation version is inefficient, try to do the following:

(1)
Provides a public swap function to efficiently replace two objects of your type. This function cannot throw an exception. This restriction is limited to the member edition of swap.

(2)
In the namespace where your class or template is located, provide a non-member swap and allow it to call the swap member function.

(3)
If you are writing a class or template, feature STD: swap for your class and ask them to call your swap function.

3,
If you call swap, make sure that it contains a using declarative so that STD: swap can be exposed and visible in your function without any namespace modifier.

 

Note:

1,
When the efficiency of STD: swap is low, a swap member function is provided and the function does not throw an exception.

2,
If you provide a members swap, you should also declare a non-member swap to call the former. For Classes instead of template, you must also specialize in STD: swap.

3,
If you call swap, make sure that it contains a using declarative so that STD: swap can be exposed and visible in your function without any namespace modifier.

4,
It is good to fully specialize STD templates for user-defined types, but do not try to add something completely new to STD in STD.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.