gpt4 book ai didi

c++ - C++中指针的奇怪行为

转载 作者:太空狗 更新时间:2023-10-29 23:37:00 24 4
gpt4 key购买 nike

以下结果非常有趣,我很难理解它们。基本上我有一个有 int 的类:

class TestClass{
public:
int test;
TestClass() { test = 0; };
TestClass(int _test) { test = _test; };
~TestClass() { /*do nothing*/ };
};

接受 TestClass 指针的测试函数

void testFunction1(TestClass *ref){
delete ref;
TestClass *locTest = new TestClass();
ref = locTest;
ref->test = 2;
cout << "test in testFunction1: " << ref->test << endl;
}

这就是我在 main 中所做的:

int main(int argc, _TCHAR* argv[])
{
TestClass *testObj = new TestClass(1);
cout << "test before: " << testObj->test << endl;
testFunction1(testObj);
cout << "test after: " << testObj->test << endl;
return 0;
}

我期望输出是:

test before: 1
test in testFunction1: 2
test after: 1

但我得到以下输出:

test before: 1
test in testFunction1: 2
test after: 2

谁能解释一下。有趣的是,将 testFunction1 更改为:

void testFunction1(TestClass *ref){
//delete ref;
TestClass *locTest = new TestClass();
ref = locTest;
ref->test = 2;
cout << "test in testFunction1: " << ref->test << endl;
}

即在将 ref 指向新位置之前我没有删除它,我得到以下输出:

test before: 1
test in testFunction1: 2
test after: 1

如果有人能向我解释这种奇怪的行为,我将不胜感激。谢谢。

最佳答案

删除对象后访问该对象时,行为未定义。

您看到的行为遵循系统中的内存分配算法。

也就是说,在删除您的第一个测试类对象之后,您为一个新对象分配内存。运行时只是重复使用内存。

要检查发生了什么,打印指针的值:

void testFunction1(TestClass *ref){
cout << ref << endl;
delete ref;
TestClass *locTest = new TestClass();
cout << locTest << endl;
ref = locTest;
ref->test = 2;
cout << "test in testFunction1: " << ref->test << endl;
}

关于c++ - C++中指针的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10706440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com