samedi 2 janvier 2021

C++ function return by value not calling move constructor [duplicate]

Here is a simple code:

#include <iostream>

using namespace std;
struct Cls {
    int i;
    Cls() {
        cout << "Inside Cls Constructor" << endl;
    }
    Cls(int i):i(i) {
        cout << "Inside Cls Constructor" << endl;
    }
    Cls(Cls const &cls) {
        cout << "Inside Copy constructor"  << endl;
        this->i = cls.i;
    }
    Cls& operator=(Cls const &o) {
        cout << "Inside assignment operator" << endl;
        this->i = o.i;
        return *this;
    }

    Cls(Cls && o) noexcept{
        this->i = o.i;
        o.i = 0;
        cout << "Inside move constructor" << endl;
    }

    ~Cls() {
        i = 0;
        cout << "Inside destructor" << endl;
    }
};

Cls getCls() {
    Cls c{20};
    cout << "Inside getCls function with c value: " << c.i << endl;
    cout << "Address of c: " << &c << endl;
    return c;
}

int main() {
    Cls d = getCls(); //getCls() suppose to be rvalue and should call move constructor of d
    d.i += 20;
    cout << "Inside main function with d value: " << d.i << endl;
    cout << "Address of d: " << &d << endl;
    return 0;
}

Output of the program:

(base) rehman@linux-desktop:/tmp/study$ g++ --version
g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

(base) rehman@linux-desktop:/tmp/study$ g++ -O0 main.cpp 
(base) rehman@linux-desktop:/tmp/study$ ./a.out 
Inside Cls Constructor
Inside getCls function with c value: 20
Address of c: 0x7ffd02d54ce4
Inside main function with d value: 40
Address of d: 0x7ffd02d54ce4
Inside destructor

1.Why no move constructor (or any constructor) is called while creating object d in the main function?

2.No matter how many times I run this, the addresses of object c and d are always the same, Isn't c suppose to be allocated in the stack of getCls() function. how that address is used in main's function stack?

Aucun commentaire:

Enregistrer un commentaire