微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

有人能够完全了解这个运算符重载函数中内存的变化吗?我很困惑在运算符函数中创建的对象如何在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:我正在引用我的教科书数据抽象&使用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:这本书错了.

解决方法

返回对本地对象的引用

正如其他人正确指出的那样,返回对本地对象的引用会导致未定义的行为.最终会得到一个被破坏的函数范围对象的句柄.

返回算术运算符中的引用

如果你考虑一下,b应该给你一个结果,但它不应该改变a或b.但是,您可以自行决定运算符如何处理您自己的类型,这样就可以实现您需要的行为.这就是运算符通常必须创建一个新对象而不能返回引用的原因.

另一方面,复合赋值(=,– =等)会改变对象本身,因此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!
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐