简体   繁体   中英

Local Variable and Variable Passed as Argument

I have doubt in following piece of code. Function fun1 and fun2 are both same. In one I have declared a local variable and in another a variable is passed by argument. Then why in case of fun1 copy constructor is not called.

#include<stdio.h>
#include<iostream>
using namespace std;
class A
{
    public:
A()
{
    printf("constructor\n");
}
A(const A&)
{
    printf("copy cons\n");
}
~A()
{
    printf("destructor\n");
}
};
A fun1()
{
A obj;
return obj;
}
A fun2(A obj)
{
return obj;
}

int main()
{
    A a=fun1();
    printf("after fun1\n");
    A b;
    A c = fun2(b);
}

Output

constructor
after fun1
constructor
copy cons
copy cons
destructor
destructor
destructor
destructor

Then why in case of fun1 copy constructor is not called?

If A has an accessible copy or move constructor, the compiler may choose to elide the copy. This is the so-called (named) return value optimization ((N)RVO) .

Because of Named Return Value Optimization , which is an optimziation the compiler performs on your code. It recognizes the fact that the return type of the function fun1() is the same as the temporary object within fun1() (of type A), so it does not create a copy of it (doesn't call the copy constructor) in the return statement.

You can try compiling your code without optimization and see if the copy constructor gets called then. If you are using the gcc compiler, the compiler flag for turning the optimization off is "-O0".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM