Complex c{ Complex{1, 2} };
为什么这条语句不会进入移动构造函数呢?
用 g++,关闭了优化 g++ -O0 main.cpp
用 visual studio 2017,也关闭了优化
#include<iostream>
using std::cout;
using std::endl;
class Complex
{
public:
Complex(double real, double image) : _real(real), _image(image)
{}
Complex(const Complex& right);
Complex(Complex&& right);
Complex& operator=(const Complex& right);
Complex& operator=(Complex&& right);
virtual ~Complex();
private:
double _real {};
double _image {};
};
Complex::Complex(const Complex& right)
{
cout << "&" << endl;
_real = right._real;
_image = right._image;
}
Complex::Complex(Complex&& right)
{
cout << "&&" << endl;
_real = right._real;
_image = right._image;
}
Complex& Complex::operator= (const Complex& right)
{
cout << "= &" << endl;
if (this != &right)
{
_real = right._real;
_image = right._image;
}
return *this;
}
Complex& Complex::operator= (Complex&& right)
{
cout << "= &&" << endl;
if (this != &right)
{
_real = right._real;
_image = right._image;
}
return *this;
}
Complex::~Complex()
{
cout << "des" << endl;
}
int main()
{
Complex c{ Complex{1, 2} };
//Complex c {std::move(Complex{1, 2})};
cout << &c << endl;
return 0;
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.