Detailed description of return value types of value assignment operators

Source: Internet
Author: User

In the study of C ++ assignment operator functions, the type of return values has been very confusing. Today, we will summarize some results of different return value types:

1. When the return value is null:

<span style="font-size:14px;">void hasptr::operator=(const hasptr& s)</span>


At this time, if there is only one '=' (a = B) operation, then there is no problem, but if there is a chain operation of '=' (a = B = C, the compiler reports an error.

Let's see: a = B = C;

The program runs B = C first;

Because the return value of the function is viod, B = C returns a null value.

This Is A = (B = C), that is, a = NULL. This operation does not exist. Even if it exists, it does not meet our original intention for this operation.


2. When the returned value is the class itself:

<span style="font-size:14px;">hasptr hasptr::operator=(const hasptr& s)</span>


Supports '=' chain operations

If the returned value is the class itself, the process of running this function is:

1. Enter the function and run the operations inside the function.

2. After the operation inside the function is completed, call the copy constructor of the class to copy the object to a new object.

3. Return the newly created object.


The key here is that every time a value assignment operator function is run, a copy constructor is called, which will not only waste time.

If the constructor is not copied to the class, errors may occur.


3. When the return value is a reference

<span style="font-size:14px;">hasptr &hasptr::operator=(const hasptr& s)</span>


This method is the best, that is, it supports chained operations and minimizes the operation time.



Complete code:

<span style="font-size:14px;">hasptr &hasptr::operator=(const hasptr& s){    i = s.i;    string *x = new string(*s.ps);    delete ps;    ps = x;    return *this;}</span>


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.