1

I've found this weird behavior in Cpp — a copy constructor is called when a function returns dereference of a pointer. The follwing code demonstrates it. I've checked this using Visual Studio community 2022 and G++.exe.

#include <iostream>
using namespace std;

class Cls1 {
public:
    Cls1() = default;
    Cls1(Cls1& other) {
        cout << "Cls1(Cls1 & other)" << endl;
    };
    Cls1(Cls1&& other) noexcept {
        cout << "Cls1(Cls1&& other)" << endl;
    };
};

Cls1 Fn1(Cls1 v) {
    return v;
}

Cls1 Fn2(Cls1 v) {
    return *(& v); // I am mentioning this line.
}

int main(int argc, char** argv) {

    Cls1 inst1;
    Cls1 inst2 = Fn1(inst1);
    Cls1 inst3 = Fn2(inst1);

    return 0;
}

The output is the following.

Cls1(Cls1 & other)
Cls1(Cls1&& other)
Cls1(Cls1 & other)
Cls1(Cls1 & other) // I expected "Cls1(Cls1&& other)" here.

Here, Fn1 calls the move constructor and Fn2 calls the copy constructor. I was surprised because I firmly expected F2 to call the move constructor as well.

Smart Humanism
  • 155
  • 1
  • 6

0 Answers0