Why do we need the copy-and-swap idiom?

Any class that manages a resource (a wrapper, like a smart pointer) needs to implement The Big Three. While the goals and implementation of the copy-constructor and destructor are straightforward, the copy-assignment operator is arguably the most nuanced and difficult. How should it be done? What pitfalls need to be avoided?

The copy-and-swap idiom is the solution, and elegantly assists the assignment operator in achieving two things: avoiding code duplication, and providing a strong exception guarantee.

How does it work?

Conceptually, it works by using the copy-constructor‘s functionality to create a local copy of the data, then takes the copied data with a swap function, swapping the old data with the new data. The temporary copy then destructs, taking the old data with it. We are left with a copy of the new data.

In order to use the copy-and-swap idiom, we need three things: a working copy-constructor, a working destructor (both are the basis of any wrapper, so should be complete anyway), and a swap function.

A swap function is a non-throwing function that swaps two objects of a class, member for member. We might be tempted to use std::swap instead of providing our own, but this would be impossible; std::swap uses the copy-constructor and copy-assignment operator within its implementation, and we‘d ultimately be trying to define the assignment operator in terms of itself!

(Not only that, but unqualified calls to swap will use our custom swap operator, skipping over the unnecessary construction and destruction of our class that std::swap would entail.)


An in-depth explanation

The goal

Let‘s consider a concrete case. We want to manage, in an otherwise useless class, a dynamic array. We start with a working constructor, copy-constructor, and destructor:

#include <algorithm> // std::copy
#include <cstddef> // std::size_t

class dumb_array
{
public:
    // (default) constructor
    dumb_array(std::size_t size = 0)
        : mSize(size),
          mArray(mSize ? new int[mSize]() : 0)
    {
    }

    // copy-constructor
    dumb_array(const dumb_array& other)
        : mSize(other.mSize),
          mArray(mSize ? new int[mSize] : 0),
    {
        // note that this is non-throwing, because of the data
        // types being used; more attention to detail with regards
        // to exceptions must be given in a more general case, however
        std::copy(other.mArray, other.mArray + mSize, mArray);
    }

    // destructor
    ~dumb_array()
    {
        delete [] mArray;
    }

private:
    std::size_t mSize;
    int* mArray;
};

This class almost manages the array successfully, but it needs operator= to work correctly.

A failed solution

Here‘s how a naive implementation might look:

// the hard part
dumb_array& operator=(const dumb_array& other)
{
    if (this != &other) // (1)
    {
        // get rid of the old data...
        delete [] mArray; // (2)
        mArray = 0; // (2) *(see footnote for rationale)

        // ...and put in the new
        mSize = other.mSize; // (3)
        mArray = mSize ? new int[mSize] : 0; // (3)
        std::copy(other.mArray, other.mArray + mSize, mArray); // (3)
    }

    return *this;
}

And we say we‘re finished; this now manages an array, without leaks. However, it suffers from three problems, marked sequentially in the code as (n).

The first is the self-assignment test. This check serves two purposes: it‘s an easy way to prevent us from running needless code on self-assignment, and it protects us from subtle bugs (such as deleting the array only to try and copy it). But in all other cases it merely serves to slow the program down, and act as noise in the code; self-assignment rarely occurs, so most of the time this check is a waste. It would be better if the operator could work properly without it.

The second is that it only provides a basic exception guarantee. If new int[mSize] fails, *this will have been modified. (Namely, the size is wrong and the data is gone!) For a strong exception guarantee, it would need to be something akin to:

dumb_array& operator=(const dumb_array& other)
{
    if (this != &other) // (1)
    {
        // get the new data ready before we replace the old
        std::size_t newSize = other.mSize;
        int* newArray = newSize ? new int[newSize]() : 0; // (3)
        std::copy(other.mArray, other.mArray + newSize, newArray); // (3)

        // replace the old data (all are non-throwing)
        delete [] mArray;
        mSize = newSize;
        mArray = newArray;
    }

    return *this;
}

The code has expanded! Which leads us to the third problem: code duplication. Our assignment operator effectively duplicates all the code we‘ve already written elsewhere, and that‘s a terrible thing.

In our case, the core of it is only two lines (the allocation and the copy), but with more complex resources this code bloat can be quite a hassle. We should strive to never repeat ourselves.

(One might wonder: if this much code is needed to manage one resource correctly, what if my class manages more than one? While this may seem to be a valid concern, and indeed it requires non-trivial try/catch clauses, this is a non-issue. That‘s because a class should manage one resource only!)

A successful solution

As mentioned, the copy-and-swap idiom will fix all these issues. But right now, we have all the requirements except one: a swap function. While The Rule of Three successfully entails the existence of our copy-constructor, assignment operator, and destructor, it should really be called "The Big Three and A Half": any time your class manages a resource it also makes sense to provide a swap function.

We need to add swap functionality to our class, and we do that as follows†:

class dumb_array
{
public:
    // ...

    friend void swap(dumb_array& first, dumb_array& second) // nothrow
    {
        // enable ADL (not necessary in our case, but good practice)
        using std::swap; 

        // by swapping the members of two classes,
        // the two classes are effectively swapped
        swap(first.mSize, second.mSize);
        swap(first.mArray, second.mArray);
    }

    // ...
};

Now not only can we swap our dumb_array‘s, but swaps in general can be more efficient; it merely swaps pointers and sizes, rather than allocating and copying entire arrays. Aside from this bonus in functionality and efficiency, we are now ready to implement the copy-and-swap idiom.

Without further ado, our assignment operator is:

dumb_array& operator=(dumb_array other) // (1)
{
    swap(*this, other); // (2)

    return *this;
}

And that‘s it! With one fell swoop, all three problems are elegantly tackled at once.

Why does it work?

We first notice an important choice: the parameter argument is taken by-value. While one could just as easily do the following (and indeed, many naive implementations of the idiom do):

dumb_array& operator=(const dumb_array& other)
{
    dumb_array temp(other);
    swap(*this, temp);

    return *this;
}

We lose an important optimization opportunity. Not only that, but this choice is critical in C++11, which is discussed later. (On a general note, a remarkably useful guideline is as follows: if you‘re going to make a copy of something in a function, let the compiler do it in the parameter list.‡)

Either way, this method of obtaining our resource is the key to eliminating code duplication: we get to use the code from the copy-constructor to make the copy, and never need to repeat any bit of it. Now that the copy is made, we are ready to swap.

Observe that upon entering the function that all the new data is already allocated, copied, and ready to be used. This is what gives us a strong exception guarantee for free: we won‘t even enter the function if construction of the copy fails, and it‘s therefore not possible to alter the state of *this. (What we did manually before for a strong exception guarantee, the compiler is doing for us now; how kind.)

At this point we are home-free, because swap is non-throwing. We swap our current data with the copied data, safely altering our state, and the old data gets put into the temporary. The old data is then released when the function returns. (Where upon the parameter‘s scope ends and its destructor is called.)

Because the idiom repeats no code, we cannot introduce bugs within the operator. Note that this means we are rid of the need for a self-assignment check, allowing a single uniform implementation of operator=. (Additionally, we no longer have a performance penalty on non-self-assignments.)

And that is the copy-and-swap idiom.

What about C++11?

The next version of C++, C++11, makes one very important change to how we manage resources: the Rule of Three is now The Rule of Four (and a half). Why? Because not only do we need to be able to copy-construct our resource, we need to move-construct it as well.

Luckily for us, this is easy:

class dumb_array
{
public:
    // ...

    // move constructor
    dumb_array(dumb_array&& other)
        : dumb_array() // initialize via default constructor, C++11 only
    {
        swap(*this, other);
    }

    // ...
};

What‘s going on here? Recall the goal of move-construction: to take the resources from another instance of the class, leaving it in a state guaranteed to be assignable and destructible.

So what we‘ve done is simple: initialize via the default constructor (a C++11 feature), then swap with other; we know a default constructed instance of our class can safely be assigned and destructed, so we know other will be able to do the same, after swapping.

(Note that some compilers do not support constructor delegation; in this case, we have to manually default construct the class. This is an unfortunate but luckily trivial task.)

Why does that work?

That is the only change we need to make to our class, so why does it work? Remember the ever-important decision we made to make the parameter a value and not a reference:

dumb_array& operator=(dumb_array other); // (1)

Now, if other is being initialized with an rvalue, it will be move-constructed. Perfect. In the same way C++03 let us re-use our copy-constructor functionality by taking the argument by-value, C++11 willautomatically pick the move-constructor when appropriate as well. (And, of course, as mentioned in previously linked article, the copying/moving of the value may simply be elided altogether.)

And so concludes the copy-and-swap idiom.


Footnotes

*Why do we set mArray to null? Because if any further code in the operator throws, the destructor of dumb_array might be called; and if that happens without setting it to null, we attempt to delete memory that‘s already been deleted! We avoid this by setting it to null, as deleting null is a no-operation.

†There are other claims that we should specialize std::swap for our type, provide an in-class swapalong-side a free-function swap, etc. But this is all unnecessary: any proper use of swap will be through an unqualified call, and our function will be found through ADL. One function will do.

‡The reason is simple: once you have the resource to yourself, you may swap and/or move it (C++11) anywhere it needs to be. And by making the copy in the parameter list, you maximize optimization.

http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom

Why do we need the copy-and-swap idiom?

时间: 2024-11-03 00:42:38

Why do we need the copy-and-swap idiom?的相关文章

c++异常安全和copy and swap策略

异常安全有两个目标: 不泄露任何资源.这个通过RAII可以做到. 不破坏数据结构.这是下文要讨论的事情 异常安全有三个级别: 基本安全:异常发生后对象和数据结构还有合法状态.实现简单,应该作为最低要求. 很安全:抛出异常后程序状态不变.即要有“原子性”,若成功则完全成功,失败则保持原状.本文的copy and swap策略即是达到这一目的的手段. 不抛出异常:总能实现功能,内置类型可以做到这一点. 所谓copy and swap策略就是先对需要修改的对象做出一份副本,这个副本的构造使用RAII以

swap function &amp; copy-and-swap idiom

在C++中,众所周知在一个资源管理类(例如含有指向堆内存的指针)中需要重新定义拷贝构造函数.赋值运算符以及析构函数(Big Three),在新标准下还可能需要定义移动构造函数和移动赋值运算符(Big Five).但实际上,这条规则还可以有一个小扩展.就是在资源管理类中,往往需要重新定义自己的swap函数来作为优化手段. 1. swap函数 首先考察如下例子,假设类HasPtr中含有一个指向string的指针 *ps 和一个int类型值value. class HasPtr { public: .

swap C++用法

1,最通用的模板交换函数模式:创建临时对象,调用对象的赋值操作符. template <class T> void swap ( T& a, T& b ) { T c(a); a=b; b=c; } 需要构建临时对象,一个拷贝构造,两次赋值操作. 2,针对int型优化: void swap(int & __restrict a, int & __restrict b) { a ^= b; b ^= a; a ^= b; } 无需构造临时对象,异或 因为指针是in

(转)谈谈C++中的swap函数

转自:http://blog.csdn.net/ryfdizuo/article/details/6435847 1,最通用的模板交换函数模式:创建临时对象,调用对象的赋值操作符. [cpp] view plain copy print? template <class T> void swap ( T& a, T& b ) { T c(a); a=b; b=c; } 需要构建临时对象,一个拷贝构造,两次赋值操作. 2,针对int型优化: [cpp] view plain co

【转】 谈谈C++中的swap函数

1,最通用的模板交换函数模式:创建临时对象,调用对象的赋值操作符. 1 template <class T> void swap ( T& a, T& b ) 2 { 3 T c(a); a=b; b=c; 4 } 5 需要构建临时对象,一个拷贝构造,两次赋值操作. 2,针对int型优化: 1 void swap(int & __restrict a, int & __restrict b) 2 { 3 a ^= b; 4 b ^= a; 5 a ^= b; 6

c++ swap 函数

转载地址 1,最通用的模板交换函数模式:创建临时对象,调用对象的赋值操作符. template <class T> void swap ( T& a, T& b ) { T c(a); a=b; b=c; } 需要构建临时对象,一个拷贝构造,两次赋值操作. 2,针对int型优化: void swap(int & __restrict a, int & __restrict b) { a ^= b; b ^= a; a ^= b; } 无需构造临时对象,异或 因为

[020]转--C++ swap函数

原文来自:http://www.cnblogs.com/xloogson/p/3360847.html 1.C++最通用的模板交换函数模式:创建临时对象,调用对象的赋值操作符 1 template <class T> void swap ( T& a, T& b ) 2 { 3 T c(a); 4 a=b; 5 b=c; 6 } 需要构建临时对象,一个拷贝构造,两次赋值操作. 2.针对int型优化: 1 void swap(int & __restrict a, int

一个自己实现的string

最近实现了一个string类,添加了一些c++11元素. 除了基本的构造析构函数,拷贝构造和赋值函数,另外添加移动拷贝和赋值函数.default是一个很方便的特性有木有. //default constructor KianString()=default; KianString(const char *c): ch_(0) { ch_ = (char*)malloc(sizeof(char)*(strlen(c)+1)); strncpy(ch_, c, strlen(c)+1); }; ~K

What are move semantics?

I find it easiest to understand move semantics with example code. Let's start with a very simple string class which only holds a pointer to a heap-allocated block of memory: #include <cstring> #include <algorithm> class string { char* data; pu

交换操作 swap

一个类定义一个swap函数通常需要一次拷贝和两次赋值 例如 A类的两个对象v1与v2交换 A temp=v1; //copy构造一个临时对象 v1=v2; //赋值运算 v2=temp;  //赋值运算 如果采用指针交换则可以减少一次拷贝构造 A* temp=v1; v1=v2; //赋值运算 v2=temp;  //赋值运算 分清swap与std::swap的使用 std::swap是标准库定义的,一般内置类型直接用即可,如果涉及自定义的类则使用自定义的swap. void swap(A& l