[英]C++ Pointer Issues when passing to a function
下面的解決方案近一年來,我以為我完全理解了指針,但是現在失敗了。 如果需要,我將發布整個文件。
// 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()
替換它並完成它。
你通過指針You
按值void Update(You*,int)
因此update = youTwo;
這對currentYou
沒有影響。
更改Update
到void Update(You*& update, in n) { //...
和引用閱讀起來。
順便說一句,您有內存泄漏。 您更新了指針,但從未取消分配舊的currentYou
或新的currentYou
。 您應該使用“智能指針”(明確地為shared_ptr<You>
)來清理背后的所有內容,而不必每次都調用delete
。
#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
),並且指針現在是一個指針引用。 完美的作品。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.