Home How is a local variable created in functions?
Reply: 0

How is a local variable created in functions?

user1111
1#
user1111 Published in June 23, 2018, 5:30 pm

Lets say I have this code:

#include <iostream>
using namespace std;

class A{
public:
    A() { cout << "In normal ctor\n"; }
    A(const A& a) { cout << "In cpy ctor\n";  }
    A(A&& a) { cout << "In move ctor\n"; }
    ~A() { cout << "In dtor\n"; }
};

A func(A a) {
    return a;
}

void main(){
    A a1;
    A a2 = func(a1);
}

The output is the following:

In normal ctor
In cpy ctor
In move ctor
In dtor
In dtor
In dtor

Now I'm having trouble understanding what's happening inside the function ''func''.

When a1 is sent to the function, the function doesn't receive it byRef,but rather it ''creates'' it's own version of a1 which is 'a'.

That's why when the function ends, the object ''dies'' and it goes the the destractor.

So why doesn't it also go to the constructer in the first place? (Assuming that a local object is really created there)

Is there any copying that's happening behind the scenes?

Thanks in advance!

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.318824 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO