2011-05-12 145 views
1

我有一個關於指針的問題兩個指針指向同一個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

回答

3

首先,您應該避免直接調用對象的析構函數。這並沒有釋放與之相關的內存。改爲使用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

相關問題