On 02/23/2017 01:35 AM, Christiano wrote:
> I saw this Code in a book[1]:
>
> Date next_Sunday(const Date &d)
> {
> // access d using d.day(), d.month(), and d.year()
> // make new Date to return
> }
>
I was testing some codes here.
See this C code:
/----------- a1.c -----------------\
#include <stdio.h>
struct house {
int a;
int b;
};
struct house func()
{
struct house e = {2,3};
return e;
}
int main()
{
int num =8;
struct house x = func();
printf("%d %d\n", x.a, x.b);
return 0;
}
\---------------------------------/
Now, see the second version:
/------------- a2.c -----------------------\
#include <stdio.h>
struct house {
int a;
int b;
};
struct house func()
{
return (struct house){2,3};
}
int main()
{
int num =8;
struct house x = func();
printf("%d %d\n", x.a, x.b);
return 0;
}
\--------------------------------------/
The "func" function in the first version locally creates a "struct
house" and then copies it to the "struct house" in the main.
The "func" function in the second version creates the "struct house" in
the main directly.
It is possible to observe this in the generated assembly code using -S
option (gcc/g++).
In C++ things are not different.
For example:
Date new_date_random()
{
Date x = Date{ random_day(), random_month(), random_year() };
return x;
}
VERSUS
Date new_date_random()
{
return Date{ random_day(), random_month(), random_year() };
}
The first version locally creates a "Date" and then copies it to the
"Date" outside. (Assuming here that there was no RVO optimization.)
The second version creates the "Date" outside directly.
That is, this information indicates that:
In situations where we are not receiving references from the object
outside, It is preferable whenever possible to return an unnamed literal
class object.