Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;按引用返回堆栈分配详细信息_C++ - Fatal编程技术网

C++ C++;按引用返回堆栈分配详细信息

C++ C++;按引用返回堆栈分配详细信息,c++,C++,有人能详细介绍一下这个操作符重载函数中的内存发生了什么吗?我对操作符函数中创建的对象如何在主函数中释放感到困惑 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& 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++ CARANO表示,这种格式的链接表的操作符+过载:<代码>链接列表和操作符+(const Link KeldListand右thand)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
}
LinkedList和operator+(常量LinkedList和rightHandSide)常量{
concatList=LinkedList的新的空实例
concatList.itemCount=itemCount+rightHandSide.itemCount
leftChain=此列表中节点链的副本
rightChain=右侧列表中节点链的副本
concatList.headPtr=leftChain.headPtr
返回目录器
}
编辑3:问我的教授这件事。明天会查清楚的


编辑4:这本书错了

这只是未定义的行为

就内存发生的情况而言,在函数返回后,内存不会保留给对象(因为对象现在超出范围)


因此它可以包含任何内容,包括通过巧合的方式包含相同的对象。

它不会导致内存泄漏,但是当函数返回时,当它超出范围时,
o
会被破坏。所以调用方的引用是垃圾。它可能会在短时间内正常工作,直到稍后内存被覆盖。

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

返回算术运算符中的引用 如果你仔细想想,
a+b
应该会给你一个结果,但它不应该改变
a
b
。然而,C++让您定义操作人员如何在自己的类型上工作,这样就可以实现您需要的行为。这就是为什么
操作符+
通常必须创建一个新对象,并且不能返回引用

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


这是未定义的行为,简单明了。不要返回对具有自动存储持续时间的对象的引用。它必须返回
*this
,而不是
o
。此代码会导致未定义的行为,并且随时可能崩溃。如果您尝试添加一些行,如
inti=1加号之后,您可以捕获它。
o
的生存期在
operator+()
函数的末尾结束。在main中使用它是未定义的行为无论如何,
操作符+
应该返回一个值而不是一个引用。教科书是否不返回对本地范围对象的引用?
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!
}