两个指针指向同一个引用
我有一个关于指针的问题
我有两个指针,一个已初始化,另一个未初始化;
现在我希望没有值(尚未初始化)的第二个指针指向内存中的同一位置。
好的,我写了一个小程序来执行此操作并且它可以正常工作
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]
架构 解释我想要的内容。
I have a question about the pointers
I have two pointers, one is initialized and the other is not;
Now i want the second pointer that has no value (is not initialized yet) to point to the same place in the memory.
OK, i wrote a small program to do this and it works correctly
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 ;
The output is like this:
P = 1 ;
P2 = 1 ;
P2 = 0 ;
So it work correct like i want.
Now i want to do the same but this time i want to do it using ID3D11Device *
Here is the code:
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 function definition :
![ID3D11Device *const Get_Device() const { return _Device ;}][1]
schema explaining what i want.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,应该避免直接调用对象的析构函数。这不会释放与其相关的内存。请改用
delete Device;
。其次,如果您想要两个指针,您只需按照第一个示例中所示的方式继续:
现在
Test
、Test2
和Device->Get_Device()
当然,只有当Device->Get_Device()
返回相同的指针时,它们才指向内存中的相同位置。编辑:参见评论
First, you should avoid calling the destructor of an object directly. That does not free the memory associated with it. Use
delete Device;
instead.Secondly, if you want two pointers you simply have to proceed as you hav shown in your first example:
now
Test
,Test2
andDevice->Get_Device()
all point to the same location in the memory of course only ifDevice->Get_Device()
returns always the same pointer.EDIT: see comment