抱歉,如果这个问题听起来太基础了,但我想知道这段代码中到底发生了什么(Point3d
是我自己的实现):
int main()
{
Point3d a(1,2,3);
Point3d b(11,12,13);
Point3d c = a+b;
Point3d d = a;
Point3d e;
return 0;
}
所以在运行上面的代码之后,函数将按以下顺序调用:
Point3d (const float x, const float y, const float z) // a
Point3d (const float x, const float y, const float z) // b
Point3d () //since I created a new object in operator+
operator+ (const Point3d& rhs) //a+b
Point3d (const Point3d& rhs) //the copy constructor for d = a
Point3d () //e
我注意到了一些事情:
- 没有为c调用构造函数
operator=
永远不会被调用(但是,如果我将赋值和实例声明放在不同的行中,operator=
就会被调用)
我观察到的是否超出预期?如果是这样,为什么从未调用过 operator=
?
附言我的 operator+ 返回一个对象而不是一个引用(Point3d 而不是 Point3d&),我认为这是正确的吗?
最佳答案
- no constructor is called for
c
很可能是由于 Return Value Optimization .
operator=
is never called
因为显示的行都没有执行任务,只有构造。在声明 和 在同一语句中分配对象的行中使用 =
只是复制构造的“语法糖”。
Point3d c = a+b; // aka: Point3d c(a+b);
Point3d d = a; // aka: Point3d d(a);
However, if I put the assignment and instance declaration in different lines,
operator=
is called
是的,如果单独的语句(不是行)用于声明和赋值,则使用operator=
。
关于c++ - 关于构造函数和运算符的一些基本问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47047485/