C++核心準(zhǔn)則C.83:對(duì)于值類類型,考慮提供一個(gè)不會(huì)拋出異常的交換...



C.83: For value-like types, consider providing a noexcept swap function
C.83:對(duì)于值類類型,考慮提供一個(gè)不會(huì)拋出異常的交換函數(shù)



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.
移動(dòng)功能可以在實(shí)現(xiàn)很多常規(guī)操作時(shí)提供便利。從順暢地移動(dòng)對(duì)象到更容易地實(shí)現(xiàn)賦值,以至提供有保證的提交函數(shù),這個(gè)函數(shù)可以為不會(huì)失敗的調(diào)用代碼提供強(qiáng)有力的支持。

Example, good(示例)
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.
為了調(diào)用者的方便,在和目標(biāo)類型同一個(gè)命名空間中提供一個(gè)非成員的swap函數(shù)。
void swap(Foo& a, Foo& b)
{
? ?a.swap(b);
}
Enforcement(實(shí)施建議)
(Simple) A class without virtual functions should have a swap member function declared.
(簡單)不包含虛函數(shù)的類就應(yīng)該定義一個(gè)swap函數(shù)。
(Simple) When a class has a swap member function, it should be declared noexcept.
(簡單)如果一個(gè)類包含一個(gè)swap成員函數(shù),這個(gè)函數(shù)應(yīng)該被聲明為noexcept。

原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c83-for-value-like-types-consider-providing-a-noexcept-swap-function
覺得本文有幫助?請(qǐng)分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
