解决方案近一年来,我认为我完全理解指针,现在它失败了。如果需要,我会发布整个文件。
// Test Structure and Function
struct You {
int x;
int y;
string str;
};
bool Show(You* showValue);
// Should (delete) in whatever way possible and update its address to the "You* update" you sent
void Update(You* update, int n) {
// Create a new "You"
You* youTwo = new You();
youTwo->x = 55;
youTwo->y = 43;
youTwo->str = "Twin";
// Update?
update = youTwo;
return;
};
bool Show(You* showValue) {
cout << "Show:" << endl;
cout << showValue->x << '\t';
cout << showValue->y << '\t';
cout << showValue->str << '\t';
cout << endl << endl;
};
int main(int argc, char** argv) {
// Original You
You* currentYou = new You();
currentYou->x = 1;
currentYou->y = 2;
currentYou->str = "You";
// Update the current you to a new you
Show(currentYou); // works
Update(currentYou, 5); // no compile errors
Show(currentYou); // shows initial values instead of the updated
return 0;
};
Update
功能是问题所在。我的意图是删除(或摆脱)原始。用new You()
替换它并完成它。
答案 0 :(得分:3)
您将You
的指针值传递给void Update(You*,int)
。因此update = youTwo;
这对currentYou
没有影响。
将Update
更改为void Update(You*& update, in n) { //...
并阅读参考资料。
currentYou
和新的currentYou
。你应该使用&#34;智能指针&#34; (明确地shared_ptr<You>
)清理你身后的一切,而不必每次都打电话给delete
。
答案 1 :(得分:0)
#include <iostream>
#include <string>
using namespace std;
// Test Structure and Function
struct You {
int x;
int y;
string str;
};
bool Show(You* showValue);
// Should (delete) in whatever way possible and update its address to the "You* update" you sent
void Update(You*& update, int n) {
// Clean Up
delete update;
// Create a new "You"
You* youTwo = new You();
youTwo->x = 55;
youTwo->y = 43;
youTwo->str = "Twin";
// Update address
update = youTwo;
return;
};
bool Show(You* showValue) {
cout << "Show:" << endl;
cout << showValue->x << '\t';
cout << showValue->y << '\t';
cout << showValue->str << '\t';
cout << endl << endl;
};
int main(int argc, char** argv) {
// Original You
You* currentYou = new You();
currentYou->x = 1;
currentYou->y = 2;
currentYou->str = "You";
// Update the current you to a new you
Show(currentYou);
Update(currentYou, 5);
Show(currentYou);
delete currentYou;
return 0;
};
内存泄漏是固定的(添加了delete
),指针现在是指针ref。效果很好。