加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 10:03:37 所属栏目:百科 来源:网络整理
导读:有人能够完全了解这个运算符重载函数中内存的变化吗?我很困惑在运算符函数中创建的对象如何在main中被释放. Object operator+(const Object other) { Object o(*this); //create instance of o that deep copies first argument ... //copy contents of oth
有人能够完全了解这个运算符重载函数中内存的变化吗?我很困惑在运算符函数中创建的对象如何在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!
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读