C ++中指针的奇怪行为 [英] Strange behavior of pointers in c++

查看:93
本文介绍了C ++中指针的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Following results are very interesting and I am having difficulty understanding them. Basically I have a class which has an int:

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

一个接受TestClass指针的测试函数

A test function which accepts a pointer of TestClass

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

这是我主要要做的:

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更改为:

Can someone explain this. Interesting thing is that changing testFunction1 to:

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

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

i.e. I do not delete ref before pointing it to new location, I get the following output:

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

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

I would really appreciate if someone can explain me this strange behavior. Thanks.

推荐答案

删除对象后访问该对象时,其行为是不确定的.

When you access the object after deleting it, the behaviour is undefined.

您看到的行为来自系统中的内存分配算法.

The behaviour that you see follows from the memory allocation algorithm in your system.

那是在删除第一个testclass对象之后,为新对象分配内存.运行时只是简单地重用内存.

That is after deleting your first testclass object, you allocate memory for a new object. The runtime simply reuses the memory.

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

To check what is going on, print the values of the pointers:

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 ++中指针的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆