两个指针指向同一个引用

发布于 2024-11-06 12:18:24 字数 1217 浏览 0 评论 0原文

我有一个关于指针的问题

我有两个指针,一个已初始化,另一个未初始化;

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

好的,我写了一个小程序来执行此操作并且它可以正常工作

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只是在用心讲痛 2024-11-13 12:18:24

首先,应该避免直接调用对象的析构函数。这不会释放与其相关的内存。请改用delete Device;

其次,如果您想要两个指针,您只需按照第一个示例中所示的方式继续:

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

现在 TestTest2Device->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:

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

now Test, Test2 and Device->Get_Device() all point to the same location in the memory of course only if Device->Get_Device() returns always the same pointer.

EDIT: see comment

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文