C++ 通过引用返回堆栈分配细节

标签 c++

有人可以详细了解这个运算符重载函数中内存发生了什么吗?我对在 operator 函数中创建的对象究竟如何在 main 中被释放感到困惑。

Object& operator+(const Object& other) {
  Object o(*this); //create instance of o that deep copies first argument
  ...
  //copy contents of other and add onto o
  return o;
}
int main() {
  Object b;
  Object c;
  Object a = b + c;
}

编辑:更具体地说,在函数中创建本地对象然后通过引用返回它不是不好的做法吗?这不会导致内存泄漏吗?

编辑 2:我引用了我的教科书Data abstraction & problem solving with c++ carrano,它建议使用以下格式的 LinkedLists 的运算符 + 重载:LinkedList<ItemType>& operator+(const LinkedList<ItemType>& rightHandSide) const; .他们按照我描述的方式实现了该方法。

编辑2.5:书中给出的完整方法伪代码:

LinkedList<ItemType>& operator+(const LinkedList<ItemType>& rightHandSide) const {
  concatList = a new, empty instance of LinkedList
  concatList.itemCount = itemCount + rightHandSide.itemCount
  leftChain = a copy of the chain of nodes in this list
  rightChain = a copy of the chain of nodes in the list rightHandSide
  concatList.headPtr = leftChain.headPtr
  return concatList
}

编辑 3:问过我的教授这件事。明天将查明真相。

编辑 4:这本书错了。

最佳答案

返回对本地对象的引用

正如其他人正确指出的那样,返回对本地对象的引用会导致未定义的行为。您最终会得到一个已销毁的函数作用域对象的句柄。

在算术运算符中返回引用

如果你考虑一下,a+b 应该给你一个结果,但它不应该改变 ab。然而,C++ 将由您来定义运算符如何在您自己的类型上工作,以便可以实现您需要的行为。这就是为什么 operator+ 通常必须创建一个新对象并且不能返回引用。

另一方面,复合赋值(+=-= 等)会更改对象本身,因此 a += b 是更改 a。这就是为什么通常通过返回引用(不是对本地对象,而是对实例本身)来实现它的原因:

Object& Object::operator+=(const Object& rhs)
{
    // do internal arithmetics to add 'rhs' to this instance
    return *this; // here we return the reference, but this isn't a local object!
}

关于C++ 通过引用返回堆栈分配细节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38740448/

相关文章:

c++ - 在 WIndows 8.1 中捕获 PC 的整个屏幕截图

c++ - 关于虚幻引擎 4 中 PlayAnimMontage 代码的问题

c++ - 使用 std::function 成员从仅移动类型构造元组

c++ - 使用#include <iostream.h>

c++ - 使每个派生类的父类成员不可修改

c++ 使用 cppunit 与 travis-ci.org 集成

c++ - 为什么 sizeof 运算符对数组产生不同的结果

C++ 指针 - visual studio 抛出异常

c++ - 调用了错误的模板函数

python - 当在另一个应用程序中嵌入 python 时,如何导入或调用子模块中的函数(即 scipy.optimize.nnls)?