C + + exception-safe assignment operator overloading "Microsoft interview 100 question 55th"

Source: Internet
Author: User

Title Requirements:

The Declaration of class cmystring is as follows:

class cmystring{public:    cmystring (char *pdata=NULL);    CMyString (const cmystring &str);     ~cmystring (void);     &operator= (const cmystring &str); Private :     Char *m_pdata;};

Implement the overloaded function of its assignment operator, which requires exception security, that is, if an exception occurs when an object is assigned, the state of the object cannot be changed.

Reference sword refers to the 1th question of offer.

Topic Analysis:

To be an exception, the state of the object does not change, we first create a temporary instance, then swap the temporary instance and the original instance.

CMyString &cmystring::operator= (const cmystring &str) {    if( this!=&str)    {        cmystring strtemp (str);         char *p = strtemp.m_pdata;         = m_pdata;         = p;    }}    

C + + exception-safe assignment operator overloading "Microsoft interview 100 question 55th"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.