Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How does C++ provide an exchange function that will not throw an exception

Shulou Source: shulou.com Published: 2022-06-01 19:12:10 10月03日 Update

This article mainly explains "how C++ provides an exchange function that will not throw an exception". The explanation in the article is simple and clear and easy to learn and understand. let's study and learn how C++ provides an exchange function that won't throw an exception.

For value class types, consider providing an exchange function that does not throw an exception

Reason (reason)

The mobility feature can provide convenience when implementing many general operations. From moving objects smoothly to making assignments easier, to providing guaranteed commit functions, this function provides strong support for calling code that does not fail.

Example, good (sample)

Class Foo {

Public:

Void swap (Foo& rhs) noexcept

{

M1.swap (rhs.m1)

Std::swap (m2, rhs.m2)

}

Private:

Bar m1

Int m2

}

For the convenience of the caller, provide a non-member swap function in the same namespace as the target type.

Void swap (Foo& a, Foo& b)

{

A.swap (b)

} Enforcement (implementation recommendations)

(Simple) A class without virtual functions should have a swap member function declared.

Classes that do not contain virtual functions should define a swap function.

(Simple) When a class has a swap member function, it should be declared noexcept.

(simple) if a class contains a swap member function, the function should be declared noexcept.

Thank you for your reading. the above is the content of "how C++ provides an exchange function that will not throw an exception". After the study of this article, I believe you have a deeper understanding of how C++ provides an exchange function that will not throw an exception, and the specific use still needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Functions clips learning content members types mobility smoothness power code functions reasons objects that is general suggestions ideas situations articles more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Docker MariaDB Huawei macOS