在递归循环中条件修改的引用内存
referenced memory conditionally modified in recursive loop
我有两个结构和一个函数
struct nodeT {
bool last;
string attribute1;
string attribute2;
string attribute3;
vector<charT> leafs;
};
struct charT {
char character;
nodeT *next;
};
void addNode(nodeT *n, string stringy, string &attribute1, string &attribute2, string &attribute3)
{
if (stringy=="") {
w->last=true;
return;
} else {
if (n->last==true) {
attribute1=n->attribute1; //these attribute fields were given values earlier
attribute2=n->attribute2;
attribute3=n->attribute3;
}
addNode(n, stringy.substr(1), attribute);
}
}
addNode
被称为
string test="";
addNode(root, "wordy", test, test, test);
问题是属性引用string &attribute
没有更改为 5,它会继续使用 ""
值进行下一次调用。
我尝试将其设置为指针引用*attribute->n->attribute
并绑了一个参考&attribute = n->attribute
这些是在黑暗中拍摄的,不起作用。
编辑:addNode
应该使用单独的内存引用调用。
string test1="";
string test2="";
string test3="";
addNode(root, "wordy", test1, test2, test3);
您是否尝试过在构造函数中初始化attribute
?
struct nodeT {
bool last;
string attribute;
vector<charT> leafs;
nodeT() : attribute("5") {}
};
你的代码看起来有点,但不完全是,不像Java... :-)
函数声明和函数调用的参数不匹配,函数 dosnt 具有变量 arg。它也不应该清除编译障碍。
贡献者做出的答案帮助我找到了答案,但他们的答案与问题略有不同。
对于设置,函数使用结构nodeT
和charT
并且被调用时相当于
root is defined globally in the class
string wordy = "hello";
string test="";
addNode(root, "wordy", test, test, test);
addNode
应该使用单独的内存引用进行调用。
string test1="";
string test2="";
string test3="";
addNode(root, "wordy", test1, test2, test3);
因此,当以后属性 1、2 和 3 被更改为唯一值时,每个属性都有一个相应的唯一内存。
相关文章:
- 对具有动态分配的内存和析构函数的类对象的引用
- 多个"常量引用"变量可以共享同一个内存吗?
- C++ 在类中使用常量引用文本时 O2 内存泄漏
- 常量引用的内存位置
- 引用释放的内存是未定义的行为吗?
- 为什么"std::uninitialized_copy"通常取消对未初始化内存的迭代器的引用不是未定
- 垃圾回收正在移动内存中被引用的对象,破坏Unreal4引擎中的引用
- X 处的指令引用了 Y 处的内存.内存无法读取
- 按引用传递和动态内存分配之间的区别是什么
- 如果引用应该保留,不删除析构函数中的指针会导致内存泄漏吗?
- 内存引用发送到双指针
- 可变引用以及指针如何与内存相互作用
- 通过引用 cpp 中的变量占用的内存
- C++中引用变量的内存?
- 来自引用指针的内存泄漏
- 在闭包中,如何通过存储在内存中的指针或引用类型捕获可变性或用现代函数式语言进行处理?
- Swift 3 引用类型和内存管理
- 数组是通过引用传递的,但是如果我只传递未存储在内存中的数组的值,会发生什么
- cpp 中的引用如何具有相同的内存地址
- 在递归循环中条件修改的引用内存