c++ - 需要帮助理解返回引用的函数

标签 c++ function reference

有什么区别

课本上写的是什么:

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/

相关文章:

c++ - glm : is not a type or namespace? 我的标题中有令人困惑的错误

function - Powershell 函数中的可重复参数(最好是链接参数集)

C++变量可以在构造函数中访问,但不能在函数中访问

c - 多维C程序结构

php - 有时我们在基于类的编码中在函数之前声明 "&"

java - Java 中每个共享引用是否占用另一个内存字(例如 32 或 64 位)?

c++ - 左值和右值返回类型以提高效率

c++ - 如何在cpp中将jpg图像转换为pgm格式

c++ - 从命令行创建 Intellisense 数据库?

c++ - 将 std::initializer_list 与 bool 重载函数一起使用时重载决议的意外行为