如下代码两个问题:
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;
};
PHP中文网2017-04-17 13:53:03
Leave opertor++
and the o
is destroyed, but a copy of o
should be returned.
Returning Coordinate
here should produce a copy, but if Coordinate&
is returned, the current code will go wrong because o
has been destroyed and its reference is useless anyway. But if your o
is out of new
, there is another problem of finding a suitable place for delete
.
Because I haven’t written C++ for many years, I’m not sure. You can debug it yourself and compare the address output of several objects to understand.
PHP中文网2017-04-17 13:53:03
1. Overloading ++ returns a local object. Will this local object be destroyed by destructor?
Yes.
2. Why is Coordinate returned instead of Coordinate&?
Returning a reference to a non-static local variable is undefined behavior.
怪我咯2017-04-17 13:53:03
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 when is preincremented, because the reference is *this
.
PHPz2017-04-17 13:53:03
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.
PHPz2017-04-17 13:53:03
First of all, if there is postfix ++ in a class, then there should be prefix ++
Then the code should be written like this:
class Coordinate{
public:
Coordinate(int x,int y):x(x),y(y){}
~Coordinate(){}
Coordinate operator++(int)
{
Coordinate o=*this;
++*this;
return o;
}
private:
int x;
int y;
};
In this case, a copy must be returned instead of a reference
天蓬老师2017-04-17 13:53:03
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.
BTY,对比前置++和后置++,对非内置类型来说,是前置++效率更高.
PHP中文网2017-04-17 13:53:03
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.