Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

Share this Page URL
Help

Construction, Destruction, and Copying > Prefer the canonical form of assignmen... - Pg. 99

Construction, Destruction, and Copying 99 55. Prefer the canonical form of assignment. Summary Your assignment: When implementing operator=, prefer the canonical form-- nonvirtual and with a specific signature. Discussion Prefer to declare copy assignment for a type T with one of the following signatures (see [Stroustrup00] and [Alexandrescu03a]): T& operator=( const T& ); T& operator=( T ); // classic // potentially optimizer-friendly (see Item 27) Settle for the second version if you would need to make a copy of the argument in- side 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 stan- dard library containers; the containers require that assignment return a plain T&. Always make copy assignment error-safe, and prefer to provide the strong guaran- tee. (See Item 71.) Ensure the assignment operator is safe for self-assignment. Avoid writing a copy as- signment operator that relies on a check for self-assignment in order to work prop- erly; often, that reveals a lack of error safety. If you write the copy assignment opera- tor 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. Re- turn *this ([Meyers97] §15). References [Alexandrescu03a] · [Cargill92] pp41-42, 95 · [Cline99] §24.01-12 · [Koenig97] §4 · [Meyers96] §33 · [Meyers97] §17 · [Murray93] §2.2.1 · [Stroustrup00] §10.4.4.1, §10.4.6.3 · [Sutter00] §13, §38, §41 · [Sutter04] §19