有什么区别
课本上写的是什么:
MyClass& Myclass::operator++() {
do something
return *this;
}
和
MyClass Myclass::operator++() {
do something
return *this;
}
*
表示“指向的值”....
是否第二个示例将返回 this 指向的对象的拷贝(*this 的拷贝),而第一个示例将返回 *this 本身?
如果是这样的话,那有什么不同呢?改善执行时间?
最佳答案
两者的区别在于
情况1
you are returning a reference ie you are returning a constant pointer to the object.
情况2
you are creating a new object and returning the object
让我们深入挖掘以更好地理解事物
情况1
since you are returning the pointer to the existing object any changes you make with affect the original object
情况2
since its a copy there is no impact on the original object
在速度和内存方面
如果是 1
since you returning the address of an existing object there is no or little overhead
情况2
you are creating a new copy ...so constructor of the object would be invoked and hence there is overhead in terms of memory and time taken
关于c++ - 需要帮助理解返回引用的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16001210/