C++ 函数按值返回不调用移动构造函数

问题描述

这是一个简单的代码

#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;
}

程序输出

(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.为什么在main函数中创建对象d时没有调用移动构造函数(或任何构造函数)?

2.无论我运行多少次,对象c和d的地址总是相同的,c不是假设分配在getCls()函数的堆栈中吗?这个地址在 main 的函数栈中是如何使用的?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)