C + + Super-faq "Assignment Operators"

Source: Internet
Author: User

    • The key to the assignment operator is the handling of the self-assignment mechanism

You need to consider self-assignment problems when overloading assignment operators, which can cause serious errors.

fred& operator= (const fred& f)

{
      // Bad code: Doesn‘t handle self-assignment!
      delete p_;                // Line #1
      p_ = new Wilma(*f.p_);    // Line #2
      return *this;

There is another error in this example, and if you throw an exception in new, P_ will become a wild pointer. The assignment action code is not intended to make the self-assignment faster. If the current code can handle the self-assignment normally (even if it is slow), then do not say if the statement is added to the assignment operator code. Since the self-assignment is rare, there is no need to make the self-assignment more efficient, and adding unnecessary if judgments can make additional assignment operations incur extra overhead. This is punishing the many to benefit the few.
    • Does the assignment operator of a derived class need to call the assignment operator of the base class?
If you create a custom assignment operator, you need to display the assignment operator that calls the base class, because the compiler does not call it automatically, and if you do not create a custom assignment operator, the compiler automatically calls the base class's assignment operator.

C + + Super-faq "Assignment Operators"

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.