如何解决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 举报,一经查实,本站将立刻删除。