Jump to content

Talk:Assignment operator (C++)

Page contents not supported in other languages.
From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 213.173.183.22 (talk) at 10:18, 27 February 2009 (proposing adding links to article "The Anatomy of the Assignment Operator" somewhere). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Example code – exception safety

The example given modifies the state of the object before all operations which might throw exceptions have completed; therefore, the example is not exception-safe. Also, it uses a built-in array, which makes exception safety difficult in general (though not for ints). Using std::vector<int> array; instead of int *array; would make exception-safety easier [1]:

class My_Array
{
        int count;
        std::vector<int> array;

public:
        // Copy constructor
        My_Array(const My_Array& orig)
                : count(orig.count), array(orig.array)
        { /* EMPTY */ }

        // Non-throwing swap
        void Swap(My_Array& orig)
        {
                using std::swap;

                swap(count, orig.count);
                swap(array, orig.array);
        }

        My_Array& operator=(const My_Array& rhs)
        {
                My_Array tmp(rhs);

                Swap(tmp);

                return *this;
        }
};
I have just refactored the code to be exception-safe. However, I've left the built-in array to show the implementation in case of manual resource management.--Tigrisek 22:22, 20 September 2007 (UTC)[reply]

Example code – Koenig Lookup

I have undid the revision since Koenig Lookup would have the same effect in this case, there's no need to complicate the code.



Surely

 std::copy(new_array, new_array + other.count, other.array);

should be

 std::copy(other.array, other.array + other.count, new_array);

? The code as-written copies from freshly allocated memory over the original :-( 213.248.204.106 (talk) 09:45, 20 October 2008 (UTC)[reply]

You're absolutely right, I've just fixed the code.Tigrisek (talk) 20:32, 22 October 2008 (UTC)[reply]

Add somewhere a Reference to "The Anatomy of the Assignment Operator"

Just as background information.