如下代码两个问题:
1,重载后置++,返回了的一个局部对象,这个局部对象是否会被析构销毁?
2,这里为什么返回的是Coordinate,而不是Coordinate& ?
class Coordinate{
public:
Coordinate(int x,int y):x(x),y(y){}
~Coordinate(){}
Coordinate operator++(int)
{
Coordinate o=*this;
++x;
++y;
return o;
}
private:
int x;
int y;
};
Leave
opertor++
and theo
is destroyed, but a copy ofo
should be returned.Returning
Coordinate
here should produce a copy, but ifCoordinate&
is returned, the current code will go wrong becauseo
has been destroyed and its reference is useless anyway. But if youro
is out ofnew
, there is another problem of finding a suitable place fordelete
.Yes.
Returning a reference to a non-static local variable is undefined behavior.
1 and 2 seem to be the same problem.
o is a local variable in operator++. If a reference to it is returned, after operator++ ends, the value of the reference will have undefined behavior, so a copy will be returned.
The reference is returned only whenis preincremented, because the reference is
*this
.The suffix ++ is different from the prefix. The semantics is to return a temporary object representing the original value, and the generated temporary object will definitely be destructed.
First of all, if there is postfix ++ in a class, then there should be prefix ++
Then the code should be written like this:
In this case, a copy must be returned instead of a reference
Returning o will cause o to be assigned to a temporary variable. If this temporary variable is referenced, it will be destroyed delayed.
It is said in the C++ Standard, Chapter 12, Section 2: Temporary Objects There are two cases of delayed destruction of temporary objects. One is used to initialize another object, and the other is that after being referenced, the temporary object is not destroyed until the reference is destroyed.
Not returning a reference is determined by post++. You must return the original object, but also have to implement the auto-increment operation. Returning a reference violates the characteristics of post++: use it first and then increment.
Because what is returned is a copied temporary value, it will be destructed when it goes out of scope. Therefore, if its reference is returned, the return value is uncertain.