【发布时间】:2017-11-28 11:15:36
【问题描述】:
这是我的代码。如果我使用 ELEM 结构的引用,我的地图将为空,否则我得到正确的值:
#include <cmath>
#include <cstdio>
#include <stack>
#include <map>
#include <iostream>
#include <string>
using namespace std;
struct ELEM;
struct ELEM {
map<string, ELEM> Children;
map<string, string> Attributes;
};
int main() {
stack<ELEM> elements;
ELEM root;
elements.push(root);
ELEM elem1;
elements.push(elem1);
elements.top().Attributes["attr1"] = "val1";
elements.top().Attributes["attr2"] = "val2";
ELEM &elem2 = elements.top(); // here is the problem ???
elements.pop();
elements.top().Children["child1"] = elem2;
cout << elements.top().Children["child1"].Attributes.size() << endl;
// i get '0'
return 0;
}
你能解释一下,有什么问题吗? 谢谢
【问题讨论】:
-
我使用 Visual Studio 2015
-
你弹出了现在被破坏的元素并且你有一个悬空引用。
-
如果你想固定元素,你必须制作 elem2
const ELEM &。因为否则它会消散。您将获得在pop之后被销毁的右值 -
@AA 这是灾难性的糟糕建议。
const表示您无法通过引用elem2更改对象。这并不意味着它会被保留。您是否在考虑可以使用临时变量初始化 const 引用的情况,在这种情况下临时变量的生命周期会延长?在这种情况下不适用 -top返回一个引用,而不是临时的。 -
"const ELEM &" 错误。我也失去了内部结构......“ELEM elem2 = elements.top();”正在工作,但它是复制(?),有什么优雅的方法吗?