社区讨论

求助 函数返回引用

学术版参与者 2已保存回复 6

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
6 条
当前快照
1 份
快照标识符
@lo3819qo
此快照首次捕获于
2023/10/24 02:18
2 年前
此快照最后确认于
2023/10/24 02:18
2 年前
查看原帖
我想通过 Treap 重载运算符像 std::map 那样在 mp[x] = y; 时修改 mp[x] 的值,我是这么写的:
CPP
define Pairing(x) Find_by_rk(Rk_of_node(x)).second

V& operator[](K x) { return Pairing(x); }
函数都是字面意思,但是编译器报错:
CPP
[Error] cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int'
我通过查资料得知:
千万不要返回局部对象的引用。当函数执行完毕时,将释放分配给局部对象的存储空间。此时,对局部对象的引用就会指向不确定的内存
于是我照猫画虎地加了 const
CPP
const V& operator[](const K &x) { return Pairing(x); }
但是问题依然没有解决,当我
CPP
printf("%d\n", mp[x]);
的时候编译器就卡住了,因为我并没有更改它的值,请问我应该怎么办?

回复

6 条回复,欢迎继续交流。

正在加载回复...