如何解决为什么我在 Visual Studio 2019 和 g++11 上为以下代码中的右值参考实现获得不同的输出?
我在复制构造函数中尝试了一个右值引用的例子,如下面的代码所示,但在不同的编译器上输出是不同的,并且能够理解为什么会出现这种差异,因为这个右值是 c++11 的概念及以后。
#include<iostream>
using namespace std;
class Test
{
/* Class data members */
int x{10};
public:
Test(Test&& t) { cout << "copy constructor called" << endl;
x = 20;
}
Test() { cout << "constructor called" << endl; }
void print() {
cout << x << endl;
}
};
Test fun()
{
cout << "fun() Called\n";
Test t;
return t;
}
int main()
{
Test t1;
t1.print();
Test t2 = fun();
t2.print();
return 0;
}
Visual Studio 2019 中的输出:
constructor called
10
fun() Called
constructor called
copy constructor called
20
gcc c++17 编译器中的输出:
constructor called
10
fun() Called
constructor called
10
为什么会出现这种差异?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。