C++指针传递给函数时出现问题
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
),指针现在是指针ref。效果完美。
相关文章:
- Visual Studio中的函数声明和函数定义问题
- C++quit()函数中可能存在作用域问题
- 类似于strcat()的函数出现问题
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 类C++中的函数问题(LNK2019和LNK1120错误)
- c++binary_search函数排序数组(流行名称搜索)出现问题
- 关于简单C++函数(is_palindrome)的逻辑的问题
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- constexpr构造函数需要常量成员函数时出现问题
- 添加存储在向量中的大整数的函数出现问题
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 关于 c++ 函数中指针赋值的简单问题
- 如何在标头中声明(或定义)函数的问题
- 有关 c++ 构造函数的问题
- 模板类转换问题 - 无法推断调用的函数
- 从 C++ 中的函数返回数组地址问题
- 关于复制构造函数的一个棘手问题
- 移动赋值运算符;尝试引用已删除的函数.我该如何解决这个问题?
- Arduino:在 loop() 和自定义函数中运行相同的代码时出现问题