两个指针指向同一个refernce

问题描述:

我有一个关于指针的问题两个指针指向同一个refernce

我有两个指针,一个被初始化,另一种是没有;

现在我想第二个指针没有值(尚未初始化)指向内存中的相同位置。

OK,我写了一个小程序来做到这一点,它工作正常

int *P , *P2 ; 
P = new int ; 
P2 = new int ; 

*P = 1 ; 
P2 = P ; 
cout << "P= " << *P << endl << endl ; 
cout << "P2= " << *P2 << endl << endl ; 

*P = 0 ; 
cout << "P2= " << *P2 << endl << endl ; 

输出是这样的:

P = 1 ; 
P2 = 1 ; 

P2 = 0 ; 

所以它的工作正确像我想要的。

现在我想要做相同的,但这次我想用ID3D11Device *

这里做的是代码:

ID3D11Device *Test ; 
Test = Device->Get_Device() ; 


cout << "Test =" << Test << endl << endl ; 
cout << "Get = " << Device->Get_Device()<< endl << endl ; 


Device->~CL_Device(); 

cout << "Test =" << Test << endl << endl ; 
cout << "Get = " << Device->Get_Device()<< endl << endl ; 

Get_Device函数定义:

![ID3D11Device *const Get_Device() const  { return _Device ;}][1] 

schema解释我想要的是。

+1

有没有我错过的问题? – forsvarir 2011-05-12 10:45:29

+2

不要使用'P2 = new int',然后在不删除旧值的情况下指向另一个内存位置。 – Benoit 2011-05-12 10:45:43

+2

你的第一个例子有内存泄漏。你分配一个新的int:'P2 = new int;',但是在重新分配指针之前不要'删除':'P2 = P;'。因此,int会一直分配,直到程序终止,浪费内存。它并不多,只是一个int,但它们很快就会加起来,特别是在循环中分配的情况下。 – 2011-05-12 10:47:18

首先,您应该避免直接调用对象的析构函数。这并没有释放与之相关的内存。改为使用delete Device;

其次,如果你想两个指针,你只需为你在你的第一个例子甲肝所示继续:

ID3D11Device *Test, *Test2; 
Test = Device->Get_Device(); 
Test2 = Test; 

现在TestTest2Device->Get_Device()都指向同一个位置当然在内存仅如果Device->Get_Device()始终返回相同的指针。

编辑:查看评论

+0

+1从来不是一个强大的词,但在这种情况下,我同意:) – Skurmedel 2011-05-12 11:12:49

+0

谢谢,你当然是对的,在某些情况下它确实有道理。 – Constantinius 2011-05-12 11:14:59