Discussion
Team LiB
Previous Section Next Section

Discussion

Prefer to declare copy assignment for a type T with one of the following signatures (see [Stroustrup00] and [Alexandrescu03a]):



T& operator=( const T& );          // classic


T& operator=( T );                 // potentially optimizer-friendly (see Item 27)



Settle for the second version if you would need to make a copy of the argument inside your operator anyway, such as the swap-based idiom featured in Item 56.

Avoid making any assignment operator virtual (see [Meyers96] §33 and [Sutter04] §19). If you think you need virtual behavior for assignment, reread those citations first. If that doesn't dissuade you and you still think you need virtual assignment, prefer to provide a named function instead (e.g., virtual void Assign( const T& );).

Don't return const T&. Although this has the benefit of preventing odd code like (a=b)=c, it has the drawback that you wouldn't be able to put T objects into standard library containers; the containers require that assignment return a plain T&.

Always make copy assignment error-safe, and prefer to provide the strong guarantee. (See Item 71.)

Ensure the assignment operator is safe for self-assignment. Avoid writing a copy assignment operator that relies on a check for self-assignment in order to work properly; often, that reveals a lack of error safety. If you write the copy assignment operator using the swap idiom (see Item 56), it will automatically be both strongly error-safe and safe for self-assignment; if self-assignment is frequent due to reference aliasing or other reasons, it's okay to still check for self-assignment anyway as an optimization check to avoid needless work.

Explicitly invoke all base assignment operators and assign all data members ([Meyers97] §16); note that swapping automatically take cares of all these things. Return *this ([Meyers97] §15).

    Team LiB
    Previous Section Next Section