C ++ core principles C.83: For value class type, consider not throw a swap function

C.83: For value-like types, consider providing a noexcept swap function

C.83: For class type value, considering not throw a swap function

 

 

Reason (reason)

A swap can be handy for implementing a number of idioms, from smoothly moving objects around to implementing assignment easily to providing a guaranteed commit function that enables strongly error-safe calling code. Consider using swap to implement copy assignment in terms of copy construction. See also destructors, deallocation, and swap must never fail.

 

 

 

 

Mobility can facilitate in the realization of many routine operations. From smoothly move the object to make it easier to achieve the assignment, as well as providing a guaranteed submission function, this function can provide strong support for the calling code does not fail.

 

 

 

Example, good (example)

 

class Foo {
public:
    void swap(Foo& rhs) noexcept
    {
        m1.swap(rhs.m1);
        std::swap(m2, rhs.m2);
    }
private:
    Bar m1;
    int m2;
};

Providing a nonmember swap function in the same namespace as your type for callers' convenience.

For convenience's call, and provide the same type of target namespace in a non-swap function members.

void swap(Foo& a, Foo& b)
{
    a.swap(b);
}
 

Enforcement (Suggestions)

 

 

 

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

  • (Simple) does not include virtual functions it 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 that should be declared as noexcept.

 

 

Description link

 

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c83-for-value-like-types-consider-providing-a-noexcept-swap-function


 

I think this article helpful? Welcome thumbs up and share it with more people.

Read more updated articles, please pay attention to micro-channel public number of object-oriented thinking []

Published 408 original articles · won praise 653 · views 290 000 +

Guess you like

Origin blog.csdn.net/craftsman1970/article/details/104864894