我有一个定义如下的类:
#include <iostream>
using namespace std;
class Point
{
int x, y;
public:
Point(int a, int b) : x(a), y(b)
{
std::cout << "Constructing point ( " << a << ", " << b << " ) "
<< std::endl;
}
Point(const Point& p) : x(p.x), y(p.y)
{
std::cout << "In copy constructor " << p.x << " " << p.y
<< std::endl;
}
Point& operator=(const Point& p)
{
std::cout << "In assignment operator " << p.x << " " << p.y
<< std::endl;
x = p.x;
y = p.y;
return *this;
}
};
int main()
{
Point p1 = Point(1, 2);
return 0;
}
现在,当我执行此操作时,我看到的是 Constructing point (1, 2)
。我假设编译器在这里做了一些优化。理论上构造一个临时对象然后调用赋值运算符来初始化 p1 是否正确?
最佳答案
不,在这样的声明中,=
运算符实际上仍然意味着调用构造函数,并且编译器可能作为优化消除了任何可能的复制构造。声明中的 =
永远不会导致调用赋值。因此理论上可以创建临时文件并将其复制构造到 p1
中。
关于C++ 隐式复制构造函数和赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5590391/