返回对本地临时对象 C++ 的引用

returning reference to local temporary object c++

本文关键字:C++ 引用 临时对象 返回      更新时间:2023-10-16

重载关系运算符 ==for class stackType返回 trueif,如果两个相同类型的堆栈相同;否则则为 false。

我的代码:

template <class Type>
const stackType<Type>& stackType<Type>::operator ==
(const stackType<Type>& otherStack)
{
    if (this->stackTop != otherStack.stackTop)
        return false;
    for (int i = 0; i < stackTop; i++)
        if (this->list[i] != otherStack.list[i])
            return false;
    return true;
} //end operator==

收到对本地临时对象警告的返回引用,据我了解,一旦函数范围结束,它就会被销毁。谁能指出我解决此警告的正确方向?

你声明你的运算符返回一个const stackType<Type>& , bt 然后你返回 truefalse 。编译器尝试将truefalse转换为const stackType<Type>&,然后将其返回。这可能不是您的意图 - 而是声明它以返回bool.

即使转换有效,引用也是对局部变量的引用,该变量给出 UB。