我有一個關於指針的問題兩個指針指向同一個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解釋我想要的是。
有沒有我錯過的問題? – forsvarir 2011-05-12 10:45:29
不要使用'P2 = new int',然後在不刪除舊值的情況下指向另一個內存位置。 – Benoit 2011-05-12 10:45:43
你的第一個例子有內存泄漏。你分配一個新的int:'P2 = new int;',但是在重新分配指針之前不要'刪除':'P2 = P;'。因此,int會一直分配,直到程序終止,浪費內存。它並不多,只是一個int,但它們很快就會加起來,特別是在循環中分配的情況下。 – 2011-05-12 10:47:18