返回对本地临时对象 C++ 的引用
returning reference to local temporary object c++
重载关系运算符 ==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 然后你返回 true
或 false
。编译器尝试将true
和false
转换为const stackType<Type>&
,然后将其返回。这可能不是您的意图 - 而是声明它以返回bool
.
即使转换有效,引用也是对局部变量的引用,该变量给出 UB。
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 强制转换为引用类型
- 引用一个已擦除类型(void*)的指针
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 具有默认值的引用获取函数
- 如何使用基类指针引用派生类成员
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 如何引用基类的派生类?